我正在使用日志记录模块打印一些数据。这是我的代码:
logging.basicConfig(
format="%(asctime)s [%(threadName)s] [%(levelname)s] %(message)s",
level=logging.INFO,
handlers=[
logging.FileHandler("{0}/{1}.log".format(logPath, fileName)),
logging.StreamHandler(sys.stdout)
]
)
我想将一些数据附加到线程名称的末尾,如下所示:
2018-10-30 19:43:54,304 [Thread-2 %SOME INFO%] [WARNING] Foo bar baz
我该怎么做?
最佳答案
Logger
类的“log”方法(调试、信息、警告等)可以采用一个额外
参数,该参数是一个字典,可以用作自定义属性。 documentation说:
The second keyword argument is
extra
which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages.
在您的示例中,我们必须在 format
属性中添加新信息:
logging.basicConfig(
format="%(asctime)s [%(threadName)s %(threadInfo)s] [%(levelname)s] %(message)s",
level=logging.INFO,
handlers=[
logging.FileHandler("{0}/{1}.log".format(logPath, fileName)),
logging.StreamHandler(sys.stdout)
]
)
我们可以像这样调用日志方法:
logging.info("Foo bar baz", extra={'threadInfo': 'SOME INFO'})
关于python - 将字符串添加到线程名称末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53069517/