【发布时间】:2020-06-03 09:36:25
【问题描述】:
当我从 Django 管理命令发出日志语句时,它们总是会加入一个大日志语句以执行整个命令。相反,我希望它们像通常的应用程序日志一样逐行单独发布。这样,日志聚合可以正确地提取它们,而不是作为一条非常大的消息。
LOGGING_ROOT_HANDLERS = ['prometheus', 'console']
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'json': {
'()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
'fmt': '%(levelname)s %(levelno)s %(pathname)s %(funcName)s %(asctime)s %(message)s',
},
},
'filters': {
'require_debug_true': {'()': 'django.utils.log.RequireDebugTrue'},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'json',
},
'prometheus': {
'level': 'WARNING',
'class': 'app.logging_handlers.PrometheusHandler',
},
},
'loggers': {
'': {'level': 'INFO', 'handlers': LOGGING_ROOT_HANDLERS},
'myapp.management.commands': {
'handlers': LOGGING_ROOT_HANDLERS.copy(),
'level': 'INFO',
'propagate': True,
},
'django': {
'handlers': LOGGING_ROOT_HANDLERS.copy(),
'level': 'WARNING',
'propagate': False,
},
'django.request': {
'handlers': LOGGING_ROOT_HANDLERS.copy(),
'level': 'INFO',
'propagate': False,
},
},
}
import logging
from django.core.management.base import BaseCommand
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
logger.info("Message %s", "1")
logger.info("Message %s", "2")
当前输出:
{"levelname": "INFO", "levelno": 20, "pathname": "runcommand.py", "funcName": "<module>", "asctime": "2020-06-03 09:32:19,497", "message": ""}
{"levelname": "WARNING", "levelno": 30, "pathname": "runcommand.py", "funcName": "<module>", "asctime": "2020-06-03 09:32:19,498", "message": "{\"levelname\": \"INFO\", \"levelno\": 20, \"pathname\": \"/www/app/myapp/management/commands/mycommand.py\", \"funcName\": \"handle\", \"asctime\": \"2020-06-03 09:32:19,345\", \"message\": \"Message 1\"}\n{\"levelname\": \"INFO\", \"levelno\": 20, \"pathname\": \"/www/app/myapp/management/commands/mycommand.py\", \"funcName\": \"handle\", \"asctime\": \"2020-06-03 09:32:19,345\", \"message\": \"Message 1\"}\n{\"levelname\": \"INFO\", \"levelno\": 20, \"pathname\": \"/www/app/myapp/management/commands/mycommand.py\", \"funcName\": \"handle\", \"asctime\": \"2020-06-03 09:32:19,345\", \"message\": \"Message 2\"}\n{\"levelname\": \"INFO\", \"levelno\": 20, \"pathname\": \"/www/app/myapp/management/commands/mycommand.py\", \"funcName\": \"handle\", \"asctime\": \"2020-06-03 09:32:19,345\", \"message\": \"Message 2\"}\n"}
{"levelname": "INFO", "levelno": 20, "pathname": "runcommand.py", "funcName": "<module>", "asctime": "2020-06-03 09:32:19,498", "message": "script \"python manage.py mycommand\" exited with 0"}
如何将第二行改为 2 行?我不希望将消息聚合为一个。 - 如果我从命令中发出正常的print 语句,甚至会发生这种情况。
【问题讨论】: