如何在日志消息中添加当前日期和时间前缀?

Dav*_*ave 1 python django logging django-3.0 python-3.9

我正在使用 Python 3.9 和 Django 3.2。我在 settings.py 文件中配置了日志记录

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}
Run Code Online (Sandbox Code Playgroud)

当我登录我的一门课程时,我会这样做

import logging
...
class TransactionService:
    def __init__(self):
        self._logger = logging.getLogger(__name__)


    def my_method(self, arg1, arg2):
            ...
        self._logger.info("Doing some logging here.")
      

  
Run Code Online (Sandbox Code Playgroud)

如何配置记录器,以便在打印消息时以当前日期和时间为前缀?

Vin*_*jip 5

这对我有用(改编自 thorndeux 的答案):

import logging.config

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'prepend_date': {
            'format': '{asctime} {levelname}: {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'prepend_date',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}

logging.config.dictConfig(LOGGING)
logging.info('foo')
logging.warning('bar')
Run Code Online (Sandbox Code Playgroud)

印刷

2021-11-28 16:05:13,469 INFO: foo
2021-11-28 16:05:13,469 WARNING: bar
Run Code Online (Sandbox Code Playgroud)