Skip to content

Instantly share code, notes, and snippets.

@archatas
Last active August 21, 2024 20:29
Show Gist options
  • Save archatas/94e7feba3d074eea78cb9e743a33829f to your computer and use it in GitHub Desktop.
Save archatas/94e7feba3d074eea78cb9e743a33829f to your computer and use it in GitHub Desktop.
Performance Logging Decorator
import time
from functools import wraps
import logging
import inspect
from django.conf import settings
SHOULD_LOG_PERFORMANCE = getattr(settings, "SHOULD_LOG_PERFORMANCE", False)
PERFORMANCE_LOGGER_NAME = "django.performance"
def log_function_time(func):
"""
Decorator to log the time taken by a function call and the function arguments.
"""
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
if SHOULD_LOG_PERFORMANCE:
# Get the function arguments
arg_spec = inspect.getfullargspec(func)
arg_names = arg_spec.args
arg_values = args
# Format the argument information
arg_info = ", ".join(
f"{name}={value}" for name, value in zip(arg_names, arg_values)
)
if kwargs:
kwargs_info = ", ".join(
f"{name}={value}" for name, value in kwargs.items()
)
arg_info += f", {kwargs_info}"
performance_logger = logging.getLogger(PERFORMANCE_LOGGER_NAME)
performance_logger.info(
f"Function '{func.__name__}' took {end_time - start_time:.6f} seconds to execute with arguments: {arg_info}"
)
return result
return wrapper
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"performance_file": {
"level": "INFO",
"class": "logging.handlers.RotatingFileHandler",
"filename": BASE_DIR / "tmp" / "performance.log",
"formatter": "verbose",
"maxBytes": 1024 * 1024, # 1 MB
"backupCount": 3,
},
"default_file": {
"level": "INFO",
"class": "logging.handlers.RotatingFileHandler",
"filename": BASE_DIR / "tmp" / "django.log",
"formatter": "verbose",
"maxBytes": 1024 * 1024, # 1 MB
"backupCount": 3,
},
},
"formatters": {
"verbose": {
"format": "%(asctime)s %(levelname)s: %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
}
},
"loggers": {
"django": {
"handlers": ["default_file"],
"level": "INFO",
"propagate": True,
},
"django.performance": {
"handlers": ["performance_file"],
"level": "INFO",
"propagate": False,
},
},
}
SHOULD_LOG_PERFORMANCE = True
from huey.contrib.djhuey import db_task
from utils.performance import log_function_time
@db_task()
@log_function_time
def do_what_needs_to_be_done(arg1, arg2, arg3="value3"):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment