You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在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 request object, 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)s variable will now be usable in any formatter attached to a handler that uses the user_context filter.

内容的提问来源于stack exchange,提问作者Alberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:30:59