13.9. Logging Use Cases
13.9.1. Use Case - 1
import logging
import os
logging.basicConfig(
format='"{asctime}", "{levelname}", "{message}"',
filename='...',
style='{'
)
log = logging.getLogger(__name__)
level = os.getenv('LOG_LEVEL', 'INFO')
log.setLevel(level)
log.critical('Critical error... finishing')
log.error('Some problem but can continue')
log.warning('Warning, this is important')
log.info('Typical message')
log.debug('Debug message with extra information')
logging.getLogger('requests').setLevel('DEBUG')
logging.getLogger('_tmp').setLevel('ERROR')
13.9.2. Use Case - 2
from datetime import datetime
import logging
logging.basicConfig(
level='DEBUG',
datefmt='%Y-%m-%d %H:%M:%S',
format='[{levelname}] {message}',
style='{'
)
def timeit(func):
def wrapper(*args, **kwargs):
time_start = datetime.now()
result = func(*args, **kwargs)
time_end = datetime.now()
time = time_end - time_start
logging.debug(f'Time: {time}')
return result
return wrapper
def debug(func):
def wrapper(*args, **kwargs):
function = func.__name__
logging.debug(f'Calling: {function=}, {args=}, {kwargs=}')
result = func(*args, **kwargs)
logging.debug(f'Result: {result}')
return result
return wrapper
@timeit
@debug
def add_numbers(a, b):
return a + b
add_numbers(1, 2)
# [DEBUG] Calling: function='add_numbers', args=(1, 2), kwargs={}
# [DEBUG] Result: 3
# [DEBUG] Time: 0:00:00.000105
add_numbers(1, b=2)
# [DEBUG] Calling: function='add_numbers', args=(1,), kwargs={'b': 2}
# [DEBUG] Result: 3
# [DEBUG] Time: 0:00:00.000042
add_numbers(a=1, b=2)
# [DEBUG] Calling: function='add_numbers', args=(), kwargs={'a': 1, 'b': 2}
# [DEBUG] Result: 3
# [DEBUG] Time: 0:00:00.000040
13.9.3. Use Case - 3
>>> from datetime import datetime
>>> from uuid import uuid1
>>> import logging
>>>
>>>
>>> logging.basicConfig(
... level='WARNING',
... datefmt='%Y-%m-%d %H:%M:%S',
... format='[{levelname}] {message}',
... style='{'
... )
>>>
>>>
>>> class MyError(Exception):
... def __init__(self, *args, **kwargs):
... self.name = self.__class__.__name__
... self.reason = self.args[0]
...
... # make a UUID based on the host ID and current time
... self.uuid = str(uuid1())
...
... # save when exception occurred
... self.when = datetime.now()
...
... # run normal processing of the exception
... super().__init__(*args, **kwargs)
>>>
>>>
>>> def run():
... raise MyError('Error, because it is not working')
>>>
>>>
>>> try:
... run()
... except Exception as error:
... name = self.name
... reason = self.reason
... when = error.when.strftime('%Y-%m-%d %H:%M:%S')
... identifier = error.uuid
...
... # you can write this error to the database
... # or print it on the stderr
... logging.error(f'Error happened: {name=}, {reason=}, {when=}, {identifier=}')
[ERROR] Error happened: name='MyError', reason='Error, because it is not working', when='1969-07-21 02:56:15', identifier='886a59c4-8431-11ec-95bc-acde48001122'