uwsgi 启动的我的 Django 应用程序中的日志记录在哪里?

Where is the logging in my Django application started by uwsgi?

我使用 supervisoruwsgi 来启动我的 Django。这是主管中的conf

[program:myapp]
directory=/home/users
command=uwsgi --ini uwsgi.ini
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=30
stderr_logfile=/var/log/supervisor/supervisor.log
stdout_logfile=/var/log/supervisor/supervisor.log

这是 uwsgi

ini 文件
[uwsgi]
http-socket=0.0.0.0:8080
wsgi-file=myapp/wsgi.py
logformat=%(ltime) "%(method) %(uri) %(proto)" status=%(status) res-time=%(msecs)ms
logto=/var/log/supervisor/uwsgi.log

这样,下面只列出方法、状态、回复时间等

14/Jan/2022:13:19:46 +0800 "GET /model/task/?taskid=e69a757974f811ec93e1f58ac6e34980&current=1&pageSize=10000&total=0&model_id=1 HTTP/1.1" status=200 res-time=107ms
14/Jan/2022:13:19:45 +0800 "POST /model/runmodel/ HTTP/1.1" status=200 res-time=3508ms

我想要的是,如果我在我的应用程序中添加一个logging.infologging.debug,它也可以写入日志文件。从 doc of uwsgi 看来,我无法通过 logformat 参数来实现。任何人都知道是否可以这样做?

美好的一天!

你是对的,logformat 只处理 uwsgi 的日志记录。

如果您希望 Django 应用记录事件,您需要添加两件事:

  1. 更新settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    "formatters": {
        "verbose": {
            "format": "[{asctime}] {levelname}: {name}.{message}",
            "style": "{",
        },
    },

    'handlers': {
         "console": {'level': 'DEBUG', "class": "logging.StreamHandler", "formatter": "verbose"},
    },
    "root": {
        "handlers": ["console"],
        "level": "DEBUG",
    },
}
  1. 然后在你要登录的地方添加如下3行代码,如下图所示:
from django.views.generic import TemplateView
from logging import getLogger # This 


logger = getLogger(__name__) # This

# Create your views here.
class IndexView(TemplateView):
    template_name = "index.html"

    def get(self, request, *args, **kwargs):
        logger.info("Index page requested") # And this
        return super().get(request, *args, **kwargs)

这将呈现以下内容:

[2022-01-14 07:09:39,874] INFO: logged.views.Index page requested
14/Jan/2022:07:09:39 +0000 "GET / HTTP/1.1" status=200 res-time=18ms

Django 文档:https://docs.djangoproject.com/en/4.0/topics/logging

查看源码:https://github.com/almazkun/uwsgi_logging