Python的日志记录格式可以根据消息日志级别进行修改吗?
我正在使用 Python 的 logging
机制将输出打印到屏幕上。我可以使用打印语句来做到这一点,但我希望允许用户更精细地调整粒度来禁用某些类型的输出。我喜欢打印错误的格式,但当输出级别为“信息”时更喜欢更简单的格式。
例如:
logger.error("Running cmd failed")
logger.info("Running cmd passed")
在这个例子中,我希望以不同的方式打印错误的格式:
<前><代码># 错误 2009 年 8 月 27 日 - 错误:运行 cmd 失败 # 信息 运行cmd通过
是否可以在不使用多个日志记录对象的情况下为不同的日志级别使用不同的格式?我希望在创建记录器后不对其进行修改,因为有大量的 if/else 语句来确定如何记录输出。
I'm using Python's logging
mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."
For example:
logger.error("Running cmd failed")
logger.info("Running cmd passed")
In this example, I would like the format of the error to be printed differently:
# error Aug 27, 2009 - ERROR: Running cmd failed # info Running cmd passed
Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我刚刚遇到这个问题,并且无法填补上面示例中留下的“漏洞”。这是我使用的更完整、更有效的版本。希望这对某人有帮助:
编辑:
Halloleo 的赞美,这里是如何在脚本中使用上述内容的示例:
编辑 2:
Python3 日志记录发生了一些变化。请参阅此处了解 Python3 方法。
I just ran into this issue and had trouble filling in the "holes" left in the above example. Here's a more complete, working version that I used. Hopefully this helps someone:
Edit:
Compliments of Halloleo, here's an example of how to use the above in your script:
Edit 2:
Python3 logging has changed a bit. See here for a Python3 approach.
是的,您可以通过自定义
Formatter
类来完成此操作:然后将
MyFormatter
实例附加到您的处理程序。Yes, you can do this by having a custom
Formatter
class:Then attach a
MyFormatter
instance to your handlers.一种方法是
定义一个类
实例化记录器
并使用!
结果
One way of doing this
Define a class
Instantiate logger
And use!
Result
再次像 JS 答案但更紧凑。
And again like JS answer but more compact.
您还可以创建一个格式化程序,根据 record.levelno (或其他条件)委托给其他格式化程序,而不是依赖样式或内部字段。以我的愚见,这是一个稍微干净的解决方案。下面的代码应该适用于任何Python版本> = 2.7:
简单的方法看起来像这样:
但是你可以让它更通用:
我在这里使用了一个字典作为输入,但显然你也可以使用元组,**kwargs,任何能让你的船漂浮的东西。然后将像这样使用:
Instead of relying on styles or internal fields, you could also create a Formatter that delegates to other formatters depending on record.levelno (or other criteria). This is a slightly cleaner solution in my humble opinion. Code below should work for any python version >= 2.7:
The simple way would look something like this:
But you could make it more generic:
I used a dict as input here, but obviously you could also use tuples, **kwargs, whatever floats your boat. This would then be used like:
这是 estani 的答案对
logging.Formatter
新实现的改编,现在依赖于格式化样式。我的依赖于'{'
样式格式,但它可以进行调整。可以细化为更通用,并允许选择格式样式和自定义消息作为__init__
的参数。This is an adaptation of estani's answer to the new implementation of
logging.Formatter
which now relies on formatting styles. Mine relies on'{'
style format, but it can be adapted. Could be refined to be more general and allow selection of formatting style and custom messages as arguments to__init__
, too.上述解决方案适用于 3.3.3 版本。
但是,在 3.3.4 中,您会收到以下错误。
类型错误:“元组”对象不可调用
在日志记录类中进行一些搜索后
库\logging__init__.py
我发现数据结构已从 3.3.3 更改为 3.3.4,导致问题
3.3.3
因此更新的解决方案是
: StringTemplateStyle }3.3.4
因此更新的解决方案是
The above solution works with 3.3.3 release.
However with 3.3.4 you get the following error.
TypeError: 'tuple' object is not callable
After some searching around in the logging class
Lib\logging__init__.py
I found that a data structure has changed from 3.3.3 to 3.3.4 that causes the issue
3.3.3
The updated solution is therefore
: StringTemplateStyle }3.3.4
The updated solution is therefore
如果您只是想跳过格式化某些级别,您可以做一些比其他答案更简单的事情,如下所示:
这也具有在 3.2 版本之前和之后工作的优点,不使用 self._fmt 或 self._style 等内部变量。
If you are just looking to skip formatting certain levels, you can do something simpler than the other answers like the following:
This also has the advantage of working before and after the 3.2 release by not using internal variables like self._fmt nor self._style.