我有带 socket.io 的 django rest 框架应用程序。为了在暂存中运行它,我使用 gunicorn 作为 WSGI 服务器,使用 GeventWebSocketWorker 作为工作者。我要解决的问题是没有像这样的 Web 请求的日志:
[2023-02-10 10:54:21 -0500] [35885] [DEBUG] GET /users
这是我的 gunicorn.config.py:
worker_class = "geventwebsocket.gunicorn.workers.GeventWebSocketWorker"
bind = "0.0.0.0:8000"
workers = 1
log_level = "debug"
accesslog = "-"
errorlog = "-"
access_log_format = "%(h)s %(l)s %(u)s %(t)s '%(r)s' %(s)s %(b)s '%(f)s' '%(a)s'"
这是我使用 deploy app 在 docker compose 中的命令:
command:
- gunicorn
- my_app.wsgi:application
我看到这个问题在 gitlab 中被讨论过:https://gitlab.com/noppo/gevent-websocket/-/issues/16 但我仍然不知道如何解决它。
看起来您已经将 gunicorn 设置配置为输出调试级别的日志,因此您正在寻找的日志可能被写入控制台输出或错误流而不是日志文件。
您可以尝试的一件事是使用 --access-logfile 和 --error-logfile 选项将控制台输出和错误流重定向到日志文件,如下所示:
accesslog = "/path/to/access.log"
errorlog = "/path/to/error.log"
这会将访问和错误日志重定向到指定的文件,而不是将它们写入控制台输出。然后您可以检查日志文件以查看是否正在那里写入调试级别的日志。
或者,你可以尝试使用像 Python 内置的日志模块这样的日志库来输出更详细的日志。这是一个可能适用于您的用例的示例配置:
import logging
# Create a logger with the name of your application
logger = logging.getLogger('my_app')
# Set the logging level to debug
logger.setLevel(logging.DEBUG)
# Create a stream handler to output logs to the console
handler = logging.StreamHandler()
# Add a formatter to the handler to format the log messages
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')
handler.setFormatter(formatter)
# Add the handler to the logger
logger.addHandler(handler)
您可以将此代码放在一个名为 logging_config.py 的文件中,然后将其导入您的 Django 设置文件并将其添加到 LOGGING 设置中:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'DEBUG',
},
'loggers': {
'my_app': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
这将配置记录器以将带有时间戳、日志级别和消息的日志消息输出到控制台。然后,您可以在 Django 视图或其他代码中添加日志语句,以在发生某些事件时输出调试级别的日志:
import logging
logger = logging.getLogger('my_app')
def my_view(request):
logger.debug(f'GET {request.path}')
# ... rest of the view logic ...
当使用 GET 请求访问视图时,这将输出类似 [2023-02-19 09:12:43,244] [DEBUG] GET /users 的日志消息。
希望对您有所帮助!
尝试将
- --access-logfile=/path/to/access.log
参数添加到您的 gunicorn 命令以写入文件或 - --access-logfile=-
以写入标准输出。