我们希望记录正在记录的文件的路径.

例如,我有一个文件views.py-此文件名在Django项目的许多应用程序中重复,因此我们需要在文件名中包含应用程序名-Polls\views.py 另一方面,我们不想要完整的绝对路径..

以下是格式行:

format": "{levelname}: {message} at {asctime} in {filename} {funcName} {lineno} (process={process: d}, thread={thread:d})"

根据this thread,我们只有以下相关选项:文件名、模块和路径名,这些选项都不够用.

还没有找到来自Django logging docs的帮助

我还try 了使用{os.path.dirname(路径名)}操作字符串,但似乎无法正确解析

我们会得到

    raise ValueError('Unable to configure '
ValueError: Unable to configure formatter 'verbose'

这是我们的settings.py中的日志(log)记录片段:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            "format": "{levelname}: {message} at {asctime} in {filename} {funcName} {lineno} (process={process: d}, thread={thread:d})",
            "style": "{",
        },
        'default': {
            'format': '%(asctime)s - %(levelname)s - %(module)s - %(lineno)d => %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S'
        },
    },
    'handlers': {
        'error_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'DEBUG',
            'formatter': 'verbose',
            'filename': f'logs/error_{datetime.datetime.today().strftime("%Y-%m-%d")}.log',
        },
        'info_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'INFO',
            'formatter': 'verbose',
            'filename': f'logs/info_{datetime.datetime.today().strftime("%Y-%m-%d")}.log',
        },
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'default',
        },
    },
    'loggers': {
        'error_logger': {
            'handlers': ['error_file', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'info_logger': {
            'handlers': ['info_file', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

推荐答案

您可以try 使用额外的上下文,如本post中所述.

在您的视图中,将您的应用程序添加为额外的上下文:

import logging

logger = logging.getLogger(__name__)

def my_function():
    app_name = 'my_app'  # Replace with your app name
    logger.info('This is a log message', extra={'app_name': app_name})

在settings.py中,在格式化程序中添加‘{app_name}’,例如:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            "**format": "{levelname}: {message} at {asctime} in {filename} {funcName} {lineno} (process={process: d}, thread={thread:d})"**,
            "style": "{",
        },
        'default': {
            'format': '%(asctime)s - %(levelname)s - %(module)s - %(lineno)d => %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S'
        },
        # Add a new formatter for including the app_name with your desired format
        'app_formatter': {
            'format': '{levelname}: {message} {asctime} {module} {app_name} {filename} {funcName} {lineno} {process:d} {thread:d} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'error_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'DEBUG',
            'formatter': 'verbose',
            'filename': f'logs/error_{datetime.datetime.today().strftime("%Y-%m-%d")}.log',
        },
        'info_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'level': 'INFO',
            'formatter': 'verbose',
            'filename': f'logs/info_{datetime.datetime.today().strftime("%Y-%m-%d")}.log',
        },
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'app_formatter',  # Use the new app_formatter
        },
    },
    'loggers': {
        'error_logger': {
            'handlers': ['error_file', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'info_logger': {
            'handlers': ['info_file', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

Python相关问答推荐

调查TensorFlow和PyTorch性能的差异

使用子字符串动态更新Python DataFrame中的列

每个组每第n行就有Pandas

telegram 机器人API setMyName不起作用

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

过载功能是否包含Support Int而不是Support Int?

如何在Python中使用时区夏令时获取任何给定本地时间的纪元值?

在函数内部使用eval(),将函数的输入作为字符串的一部分

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

使用mySQL的SQlalchemy过滤重叠时间段

点到面的Y距离

从dict的列中分钟

如何在虚拟Python环境中运行Python程序?

迭代嵌套字典的值

创建可序列化数据模型的最佳方法

删除marplotlib条形图上的底边

调用decorator返回原始函数的输出

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

在两极中过滤

寻找Regex模式返回与我当前函数类似的结果