使用带有logging.config的TimedRotatingFileHandler日志记录

PDS*_*tat 8 python logging

我正在尝试使用带有logging.config文件的TimedRotatingFileHandler进行测试,没有任何复杂但它应该每10秒滚动到一个新的日志文件中.

但是我得到以下内容

Traceback (most recent call last):
  File "testLogging.py", line 6, in <module>
    logging.config.fileConfig(logDir+'logging.conf')
  File "C:\Python26\Lib\logging\config.py", line 84, in fileConfig
    handlers = _install_handlers(cp, formatters)
  File "C:\Python26\Lib\logging\config.py", line 159, in _install_handlers
    h = klass(*args)
  File "C:\Python26\Lib\logging\handlers.py", line 195, in __init__
    raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0
is Monday): %s" % self.when)
ValueError: You must specify a day for weekly rollover from 0 to 6 (0 is Monday)
: WHEN='S'
Run Code Online (Sandbox Code Playgroud)

python非常简单,只是设置了一个不断记录的无限循环

import logging
import logging.config

logDir = "./logs/"

logging.config.fileConfig(logDir+'logging.conf')
logger = logging.getLogger('root')

while 1==1:        
    logger.info('THIS IS AN INFO MESSAGE')
Run Code Online (Sandbox Code Playgroud)

和配置文件

[loggers]
keys=root

[logger_root]
level=INFO
handlers=timedRotatingFileHandler

[formatters]
keys=timedRotatingFormatter

[formatter_timedRotatingFormatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
datefmt=%m-%d %H:%M

[handlers]
keys=timedRotatingFileHandler

[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=INFO
formatter=timedRotatingFormatter
args=('./logs/log.out', 'when=\'S\'', 'interval=10', 'backupCount=5')
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样设置为'S'而不是'W',就像错误消息似乎表明的那样.

编辑:根据下面的答案,日志配置中的正确语法是

args=('./logs/log.out', 'S', 10, 5, None, False, False)
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 14

args=('./logs/log.out', 'when=\'S\'', 'interval=10', 'backupCount=5')
Run Code Online (Sandbox Code Playgroud)

看起来不对.试试这个

args=('./logs/log.out', when='S', interval=10, backupCount=5)
Run Code Online (Sandbox Code Playgroud)

或者可能这样

args=('./logs/log.out','S',10,5)
Run Code Online (Sandbox Code Playgroud)

  • 我认为,最后一种形式应该有效.记住 - args中的任何内容都会被有效地传递给`eval()`.我不确定你的第一个建议是否有效 - 我希望它能引发一个`SyntaxError`. (2认同)