如何将日志写入 Django 项目中的 docker 容器?

gee*_*ekt 5 python django docker

我正在尝试配置本地记录器以将日志写入 docker 容器,这样我就可以在命令显示的列表中看到日志docker[-compose] logs <container> --tail 100

在 中settings.py,我配置了LOGGING这样的变量:

 LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            'format': '[DJANGO] %(levelname)s %(asctime)s %(module)s '
                      '%(name)s.%(funcName)s:%(lineno)s: %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'default',
        }
    },
    'loggers': {
        '': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        }
    },
}
Run Code Online (Sandbox Code Playgroud)

在我需要记录器的文件中,一开始我写的是:

import logging
logger = logging.getLogger(__name__)
Run Code Online (Sandbox Code Playgroud)

然后,在我需要的代码中编写:

.......
logger.error('something happened')
.......
Run Code Online (Sandbox Code Playgroud)

当我配置记录器时,日志将显示在控制台中。但我的问题是:

当我调用上述命令时,如何在 docker 容器中显示它?

所需输出的示例:

........
web_1 | [2022-02-23 17:37:10 +0200] [9] [INFO] ASGI 'lifespan' protocol appears unsupported.
web_1 | [2022-02-23 17:37:10 +0200] [9] [INFO] Application startup complete.
web_1 | [2022-02-23 17:37:10 +0200] [10] [INFO] Application startup complete.
web_1 | My log somewhere here..
........
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Dan*_*kov 1

您在 Django 中做了所有正确的事情,使您的日志在 docker 日志中可见。我发现的唯一一件事是您将此类日志传播到更高级别的处理程序(例如gunicorn)。您有两个选择:

propagate第一个选项是通过设置来避免传播False

    'loggers': {
        '': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        }
    },
Run Code Online (Sandbox Code Playgroud)

另一个选项是配置应用程序服务器以避免过滤,但这取决于应用程序服务器的配置。