Skip to content

Instantly share code, notes, and snippets.

@edi33416
Created April 11, 2022 14:26
Show Gist options
  • Save edi33416/2bcb4f44e192ebeaadf72e8e6d04668a to your computer and use it in GitHub Desktop.
Save edi33416/2bcb4f44e192ebeaadf72e8e6d04668a to your computer and use it in GitHub Desktop.
Python function log decorator
import logging
import time
import inspect
from logging.handlers import RotatingFileHandler
from functools import wraps
class MyFormatter(logging.Formatter):
def format(self, record):
record.extra_log_arg = ""
if record.args:
record.extra_log_arg = record.args.get("extra_log_arg", "Default value")
return super().format(record)
def init_logger():
logger = logging.getLogger('my_logger')
handler = RotatingFileHandler('my_log.log', maxBytes=2**10 * 1000 * 10, backupCount=10)
handler.setFormatter(MyFormatter(
'%(asctime)s %(levelname)s: %(message)s $(extra_log_arg)s [in %(pathname)s:%(lineno)d]'))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logging.Formatter.converter = time.gmtime
logger.info("Start")
init_logger()
def log_function(func):
@wraps(func)
def wrapper(*args, **kwargs):
logger = logging.getLogger('my_logger')
signature = inspect.signature(func).bind(*args, **kwargs)
signature.apply_defaults()
logger.info(f"Enter {func.__name__}{signature}", {"extra_log_arg": "test"})
value = func(*args, **kwargs)
logger.info(f"Exit {func.__name__}", {"extra_log_arg": "test"})
return value
return wrapper
@log_function
def foo(name, value=42):
print(f"In foo with name={name}")
foo("Edi")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment