我在应用程序中使用日志记录模块时遇到问题。我正在 MacBook Pro 上的 Eclipse 中针对 LDT Python (Py 2.7) 接口(interface)(而不是 Pydev)进行工作。日志模块通过 Eclipse 工作;但是,当我将应用程序转移到 RHEL5 2.7 时,日志记录似乎根本不起作用。它不会抛出任何异常,它只是不会将任何内容记录到控制台或文件(但它会创建文件)。
代码:
# Initialize logging
log = logging.getLogger('pepPrep')
# Log to stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# Log to file
logname = 'pepPrep.' + datetime.datetime.now().strftime("%Y%m%d_%H:%M") + '.log'
filelog = logging.FileHandler(logname)
filelog.setLevel(logging.DEBUG)
# set a format
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
filelog.setFormatter(formatter)
# add the handler to the root logger
log.addHandler(console)
log.addHandler(filelog)
log.INFO('This is a test')
log.DEBUG('This is a test2')
关于如何完成这项工作有任何指示吗?
最佳答案
日志记录的默认阈值为WARNING
,因此默认情况下不输出INFO
和DEBUG
消息。为此,请添加例如
logging.getLogger().setLevel(logging.DEBUG)
获取DEBUG
和INFO
消息。
您可以通过执行以下操作来确认这是您的问题
log.warning('This is a test3')
在添加setLevel
之前,并确认警告确实输出。
关于Python 日志模块在 Mac 上记录,但在 Linux 上不记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4782208/