Source code for pypartkeepr.utils
# -*- mode: python; mode: elpy; coding: utf-8 -*-
#
# Copyright 2018-2019 Luc Chouinard lumostor@3X0.ca
#
# This file is part of pypartkeepr.
#
# pypartkeepr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pypartkeepr is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pypartkeepr. If not, see <https://www.gnu.org/licenses/>.
#
import pytz
from datetime import datetime
import logging
import functools
[docs]def pk_now():
"""return now utc
"""
now = datetime.now(pytz.utc).strftime("%Y-%m-%dT%H:%M:%S%z")
return now[:-2] + ':' + now[-2:]
[docs]def logger_border(f):
def wrapper(*args, **kwargs):
args[0].logger.debug(*args[1:], "", **kwargs)
return f(*args, **kwargs)
return wrapper
[docs]def set_logger(f):
def wrapper(*args, **kwargs):
args[0].logger = logging.getLogger('{}.{}'.format(__name__,
args[0].__class__.__name__))
return f(*args, **kwargs)
return wrapper
[docs]class log_with(object):
'''Logging decorator that allows you to log with a
specific logger.
'''
# Customize these messages
# ENTRY_MESSAGE = 'Entering {}'
# EXIT_MESSAGE = 'Exiting {}'
def __init__(self, logger=None):
self.logger = logger
def __call__(self, func):
'''Returns a wrapper that wraps func.
The wrapper will log the entry and exit points of the function
with logging.INFO level.
'''
# set logger if it was not set earlier
if not self.logger:
logging.basicConfig()
self.logger = logging.getLogger(func.__module__)
@functools.wraps(func)
def wrapper(*args, **kwds):
self.logger.info(self.ENTRY_MESSAGE.format(func.__name__))
f_result = func(*args, **kwds)
self.logger.info(self.EXIT_MESSAGE.format(func.__name__))
return f_result
return wrapper