能否在Django的settings.py的LOGGING配置formatters中添加用户信息?
Absolutely! You can include user information directly in your Django LOGGING formatters—you just need to add a custom filter to inject the user context into the log record first. Here's how to implement it step by step:
Step 1: Create a Custom Log Filter
First, define a filter class that pulls the user from the request context and adds it to the log record. You can extend Django's built-in RequestFilter to preserve existing request-related functionality:
from django.utils.log import RequestFilter class UserRequestFilter(RequestFilter): def filter(self, record): # Add user username to the log record (handle anonymous users gracefully) if hasattr(self, 'request') and self.request.user.is_authenticated: record.user = self.request.user.username else: record.user = 'anonymous' # Call parent filter method to keep default request-related behavior return super().filter(record)
Save this in a file like your_app/log_filters.py (adjust the path to match your project's structure).
Step 2: Update Your LOGGING Configuration
Modify your existing LOGGING dictionary to register the filter, attach it to a handler, and create a formatter that uses the new %(user)s variable:
LOGGING = { 'version': 1, 'disable_existing_loggers': False, # Register your custom filter 'filters': { 'user_context': { '()': 'your_app.log_filters.UserRequestFilter', # Use your actual path }, }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '[%(asctime)s] %(levelname)s [%(funcName)s:%(lineno)d] %(message)s' }, # New formatter including user info 'verbose_with_user': { 'format': '%(levelname)s %(asctime)s %(module)s %(user)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { # Example handler using the user filter and new formatter 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'filters': ['user_context'], 'formatter': 'verbose_with_user', }, # Apply the filter/formatter to other handlers (like file handlers) as needed }, 'loggers': { # Assign the handler to your app's logger 'your_app': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, }
Key Notes:
- This filter depends on access to the
requestobject, so it works seamlessly for logs generated in views, middleware, or other code with an active request context. - For background tasks (like Celery jobs) without a request, you can manually inject user info using
logger.info("Your message", extra={'user': username})if you have the user identifier available. - The
%(user)svariable will now be usable in any formatter attached to a handler that uses theuser_contextfilter.
内容的提问来源于stack exchange,提问作者Alberto

