python日志记录字符串格式 [英] python logging string formatting

查看:208
本文介绍了python日志记录字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python的日志格式化程序来格式日志记录,我有一个fmt值

  fmt =[%(filename)s:%(lineno)s]%(message)s

我想要的是将[file.py:20]扩展为10个字符(例如)。如果这是一个本来很容易的价值,但是有什么办法可以把整个结构拉伸到一定的长度?
我想要的东西是:

pre $ t $ t $ t $%
fmt =%(tmp)10s%(message)s

知道这是可能的使用字符串格式或如果我可以欺骗python的格式化程序得到我想要的东西。

解决方案

Option 1



从这里开始: http://docs.python.org/library/logging.html#formatter-objects



您将创建您自己的<$ c自定义子类$ c $>格式化程序,它提供了它自己独特的格式方法。

一定要在你的每个处理程序中调用 setFormatter(),以便它们使用新的格式化程序。



选项2



使用附加属性创建您自己的LogRecord的子类。 b

子类 Logger 并覆盖 makeRecord 来创建新的子类 LogRecord



提供使用此新属性值的自定义格式。

I am using python's log formatter to format log records and i have a fmt value of

fmt = "[%(filename)s:%(lineno)s] %(message)s"

What i would like is that "[file.py:20]" to be stretched to 10 characters wide (for example). If it was one value that would have been easy but is there any way to stretch this entire structure to a specified length? I want something like:

tmp = "[%(filename)s:%(lineno)s]"
fmt = "%(tmp)10s %(message)s"

I would like to know if this is possible using string formatting or if I can trick python's formatter somehow to get what i want..

解决方案

Option 1

Start here: http://docs.python.org/library/logging.html#formatter-objects

You'll create your own customized subclass of Formatter that provides it's own unique format method.

Then you must be sure to call setFormatter() in each of your Handlers so that they use your new formatter.

Option 2

Create your own subclass of LogRecord with the additional property.

Subclass Logger and override makeRecord to create your new subclass of LogRecord.

Provide a customized format that uses this new property value.

这篇关于python日志记录字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆