为什么python日志模块旋转日日志会一团糟?
我想在python2.7、uWSGI、master/worker、多进程中按天旋转两个日志文件。我编写了一个名为logger.py的通用记录器为什么python日志模块旋转日日志会一团糟?,python,logging,logrotate,Python,Logging,Logrotate,我想在python2.7、uWSGI、master/worker、多进程中按天旋转两个日志文件。我编写了一个名为logger.py的通用记录器 import yaml import logging, logging.config log_conf = yaml.load(open('logger.yaml')) logging.config.dictConfig(log_conf) logger = logging.getLogger('access') exc_logger = loggi
import yaml
import logging, logging.config
log_conf = yaml.load(open('logger.yaml'))
logging.config.dictConfig(log_conf)
logger = logging.getLogger('access')
exc_logger = logging.getLogger('exception')
其他模块像这样编写日志
from logger import logger, exc_logger
...
logger.error('Req index error | err=%s', e)
exc_logger.exception('Req index error')
这是配置文件logger.yaml
version: 1
disable_existing_loggers: False
formatters:
simple:
format: '%(asctime)s | %(name)8s | %(levelname)s | %(message)s'
datefmt: '%Y-%m-%d %H:%M:%S'
detailed:
format: '%(asctime)s | %(process)d | %(levelname)s | %(filename)s | %(lineno)d | %(funcName)s | %(message)s'
datefmt: '%Y-%m-%d %H:%M:%S'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: detailed
stream: ext://sys.stdout
access_file_handler:
class: logging.handlers.TimedRotatingFileHandler
level: DEBUG
formatter: detailed
filename: log/access.log
backupCount: 30
encoding: utf8
when: D
interval: 1
delay: True
exception_file_handler:
class: logging.handlers.TimedRotatingFileHandler
level: ERROR
formatter: detailed
filename: log/exception.log
backupCount: 30
encoding: utf8
when: D
interval: 1
delay: True
loggers:
access:
level: DEBUG
handlers: [console, access_file_handler]
propagate: no
exception:
level: ERROR
handlers: [console, exception_file_handler]
问题是日志的日期与文件名的日期不匹配。例如,下面是access.log.2016-02-17的日志
2016-02-19 09:43:10 | 7065 | INFO | ...
2016-02-19 09:43:10 | 7065 | INFO | ...
...
2016-02-20 09:05:59 | 7065 | INFO | ...
2016-02-20 09:05:59 | 7065 | INFO | ...
...
为什么呢?我做错什么了吗?您在配置文件中设置了delay=True 如果delay为true,则文件打开延迟到第一次调用 发射() 这意味着日志文件从第一条日志消息开始
可能存在这样一个问题:文件名是在实际打开日志文件之前定义的,导致文件名与日志文件中的日期不匹配。在阅读TimedRotatingFileHandler的源代码后,最终确定发生了什么
when
的参数应该是midnight
,而不是D
<代码>午夜表示午夜旋转。这正是我想要的
D
表示在间隔
天之后旋转。如果interval
的值为1,并且应用程序在10:00开始,则旋转将在第二天的10:00发生。同一日志文件中将有两个日期。如果在第二天9:00后重新启动应用程序,则旋转将延迟到第二天9:00后。同一个日志文件中将有三个日期。日志循环可能每天都在您开始该过程时发生。日志文件的创建日期是什么?我找不到创建时间。名为access.log.2016-02-17的文件的访问/修改/更改日期为2016-02-20。创建日期很重要。它存储文件第一次创建的时间。Linux似乎不存储创建时间。我只能在stat access.log.2016-02-17
之后才能获得访问/修改/更改时间。这很奇怪。程序每天都有日志,它每天都调用emit()。但是当天第一次调用emit()时日志没有旋转。请尝试从配置文件中删除delay=True。