简体   繁体   English

Python TimedRotatingFileHandler 记录到文件和标准错误

[英]Python TimedRotatingFileHandler logs to a file and stderr

I am trying to include simple logging into my application using TimedRotatingFileHandler.我正在尝试使用 TimedRotatingFileHandler 将简单的登录包含到我的应用程序中。 However I get the output both into the designated file and into the standard error.但是,我将 output 都放入指定文件和标准错误中。 I reduced the problem to a small example:我将问题简化为一个小例子:

import logging, logging.handlers
import sys

logging.basicConfig(format='%(asctime)s %(message)s')
loghandler = logging.handlers.TimedRotatingFileHandler("logfile",when="midnight")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(loghandler)

for k in range(5):
    logger.info("Line %d" %  k)

I get 5 log lines both in my 'logfile' and this program's stderr.我的“日志文件”和该程序的标准错误中都有 5 条日志行。 What am I doing wrong?我究竟做错了什么?

This is the way you can have the print just on the log files and not to stdout/stderr:这是您可以仅在日志文件而不是 stdout/stderr 上打印的方式:

import logging
from logging.handlers import TimedRotatingFileHandler

logHandler = TimedRotatingFileHandler("logfile",when="midnight")
logFormatter = logging.Formatter('%(asctime)s %(message)s')
logHandler.setFormatter( logFormatter )
logger = logging.getLogger( 'MyLogger' )
logger.addHandler( logHandler )
logger.setLevel( logging.INFO )

for k in range(5):
    logger.info("Line %d" %  k)

logging.basicConfig sets up a handler that prints to standard error. logging.basicConfig设置一个打印到标准错误的处理程序。 logger.addHandler(loghandler) sets up a TimedRotatingFileHandler. logger.addHandler(loghandler)设置一个 TimedRotatingFileHandler。

Do you wish to squelch output to standard error?您想将 output 压制为标准错误吗? If so, simply remove the call to logging.basicConfig .如果是这样,只需删除对logging.basicConfig的调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM