Because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a SocketHandler, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.)
有的人会说,那我不用多进程不就可以了。但是 Python 有一个 GIL 的大锁(关于 GIL 的纠葛可以看这里),使用多线程是没法利用到多核 CPU 的,大部分情况下会改用多进程来利用多核 CPU,因此我们还是绕不开不开多进程下日志的问题。
为了解决这个问题,可以使用 ConcurrentLogHandler,ConcurrentLogHandler 可以在多进程环境下安全的将日志写入到同一个文件,并且可以在日志文件达到特定大小时,分割日志文件。在默认的 logging 模块中,有个 TimedRotatingFileHandler 类,可以按时间分割日志文件,可惜 ConcurrentLogHandler 不支持这种按时间分割日志文件的方式。
重新修改下 handlers 中的>
logging.config.dictConfig({ ...
'handlers': {
'file': {
'level': 'DEBUG',
# 如果没有使用并发的日志处理类,在多实例的情况下日志会出现缺失
'class': 'cloghandler.ConcurrentRotatingFileHandler',
# 当达到10MB时分割日志
'maxBytes': 1024 * 1024 * 10,
# 最多保留50份文件
'backupCount': 50,
# If delay is true,
# then file opening is deferred until the first call to emit().
'delay': True,
'filename': 'logs/mysite.log',
'formatter': 'verbose'
}
},
...