python日志输出是否可以不带信息:

2024-04-25 23:04:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

INFO:root:post params in transmitter

我是否可以设置不带INFO:root:的python日志输出,例如:

post params in transmitter

只有我自己的日志?

太多了!


Tags: 数据ininfo框架原因rootparamspost
3条回答

当然。您可以根据需要设置格式:

format: '%(message)s'

像这样:

logging.basicConfig(format='%(message)s', ...)

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

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

那些“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)

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

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)

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

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

相关问题 更多 >