简体   繁体   English

如何配置Python 2.3日志消息的格式?

[英]How to configure format of Python 2.3 logging messages?

In Python 2.4 and later, configuring the logging module to have a more basic formatting is easy: 在Python 2.4及更高版本中,将日志记录模块配置为具有更基本的格式很容易:

logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s") logging.basicConfig(level = opts.LOGLEVEL,format =“%(message)s”)

but for applications which need to support Python 2.3 it seems more difficult, because the logging API was overhauled in Py2.4. 但是对于需要支持Python 2.3的应用程序来说似乎更加困难,因为日志API在Py2.4中进行了大修。 In particular, basicConfig doesn't take any arguments. 特别是,basicConfig不带任何参数。 Trying a variation on the sole example in the Py2.3 documentation, I get this: 尝试在Py2.3文档中的唯一示例的变体,我得到这个:

try:
    logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
except:
    logging.getLogger().setLevel(opts.LOGLEVEL)
    h = logging.StreamHandler()
    h.setFormatter(logging.Formatter("%(message)s"))
    logging.getLogger().addHandler(h)

but calling this root logger in Py2.3, eg 但是在Py2.3中调用这个根记录器,例如

logging.info("Foo")

gives duplicated output: 给出重复的输出:

Foo
INFO:root:Foo

I can't find a way to modify the format of the existing handler on the root logger in Py2.3 (the "except" block above), hence the "addHandler" call that's producing the duplicated output. 我无法找到一种方法来修改Py2.3中根记录器上的现有处理程序的格式(上面的“除”块),因此产生重复输出的“addHandler”调用。 Is there a way to set the format of the root logger without this duplication? 有没有办法设置根记录器的格式没有这种重复? Thanks! 谢谢!

except: without exception class[es] is a good way to get in trouble. except:无异常类[es]是一个很好的方法来解决问题。 I believe logging module in Python 2.3 has basicConfig() function, but with less options. 我相信Python 2.3中的logging模块具有basicConfig()函数,但选项较少。 Since it accepts **kwargs it may fail at any moment after doing some job. 由于它接受**kwargs它可能在做完一些工作后的任何时候失败。 I think it already installed a handler with default format then failed to configure something. 我认为它已经安装了一个默认格式的处理程序,然后无法配置。 After catching exception you have installed another handler. 捕获异常后,您已安装另一个处理程序。 Having 2 handlers you get 2 messages for each event. 拥有2个处理程序,您可以为每个事件获得2条消息。 The simplest way in your case: avoid using basicConfig() at all and configure logging manually. 在您的情况下最简单的方法:避免使用basicConfig()并手动配置logging And never use except: if you don't reraise or log caught exception. 永远不要使用except:如果你没有重新加入或记录被捕异常。

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

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