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)
当然。您可以根据需要设置格式:
像这样:
有关详细信息,请参阅文档:http://docs.python.org/library/logging.config.html
那些“INFO:…”或“DEBUG:…”出现在那里,因为某些处理程序定义了它。我的猜测是:默认的处理程序仍然存在。
您可以在创建logger.handlers之后查看它。
另外,您可以覆盖默认处理程序的格式:
我不是一个Python专家,所以也许有更好的方法来删除甚至不创建默认的处理程序,但这对我来说非常有效。
注意:如文档中所述,.basicConfig对于简单的记录器非常有用。如果您有多个流和多个格式,据我所知它不起作用,您需要使用自定义处理程序。
相关问题 更多 >
编程相关推荐