可以没有INFO:root的python日志输出

lit*_*ger 14 python logging

我使用Python日志框架和默认设置.对于某些数据比较原因:我必须将日志与其他数据输出进行比较.但是python日志以默认开头,例如:

INFO:root:post params in transmitter
Run Code Online (Sandbox Code Playgroud)

我可以设置python日志输出INFO:root:,如:

post params in transmitter
Run Code Online (Sandbox Code Playgroud)

只有我自己的日志?

多谢!

Ulf*_*lfR 24

当然可以.您可以将格式设置为您喜欢的watever:

format: '%(message)s'
Run Code Online (Sandbox Code Playgroud)

像这样:

logging.basicConfig(format='%(message)s', ...)
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅doc:http://docs.python.org/library/logging.config.html


Dan*_*HOP 7

那些 "INFO:..." 或 "DEBUG:..." 出现在那里是因为某些处理程序定义了它。我的猜测:默认处理程序仍然存在。

您可以在创建后立即查看 logger.handlers 来检查它。

logger = logging.getLogger()
logger.handlers = [] # This is the key thing for the question!

# Start defining and assigning your handlers here
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
Run Code Online (Sandbox Code Playgroud)

此外,您可以覆盖该默认处理程序的格式:

if (len(logger.handlers) > 0): # Check here whatever. Or try/except. You get the idea...
    formatter = logging.Formatter("%(asctime)s: %(levelname)s - %(message)s")
    logger.handlers[0].setFormatter(formatter)
Run Code Online (Sandbox Code Playgroud)

我不是 Python 专家,所以也许有更好的方法来删除甚至不创建该默认处理程序,但这对我来说效果很好。

注意:如文档中所述, .basicConfig 对于简单的记录器很有用。如果您有多个流,多种格式,据我所知它不起作用,您需要使用自定义处理程序。


Gan*_*ank 5

endDate = '2015-07-24'
logging.basicConfig(filename="win" + strftime("%Y%m%d", localtime()) + ".txt", level=logging.DEBUG,format='%(message)s')
Run Code Online (Sandbox Code Playgroud)


Amb*_*ber 2

用一个Formatter