python中的记录器链 [英] logger chain in python

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

问题描述

我正在编写python包/模块,并希望记录消息提及它们来自哪个模块/类/功能. IE.如果我运行此代码:

I'm writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code:


import mymodule.utils.worker as worker

w = worker.Worker()
w.run()

我想记录如下消息:


2010-06-07 15:15:29 INFO mymodule.utils.worker.Worker.run <pid/threadid>: Hello from worker

我该怎么做?

谢谢.

推荐答案

我倾向于在我的包/模块中使用日志记录模块,如下所示:

I tend to use the logging module in my packages/modules like so:

import logging
log = logging.getLogger(__name__)
log.info("Whatever your info message.")

这会将记录器的名称设置为要包含在日志消息中的模块的名称.您可以通过在格式字符串中找到%(name)s的位置来控制名称的位置.同样,您可以将pid与%(process)d放置在一起,并将线程ID与%(thread)d放置在一起. 查看文档以了解所有选项.

This sets the name of your logger to the name of the module for inclusion in the log message. You can control where the name is by where %(name)s is found in the format string. Similarly you can place the pid with %(process)d and the thread id with %(thread)d. See the docs for all the options.

格式示例:

import logging
logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s %(process)d/%(threadName)s: %(message)s")
logging.getLogger('this.is.the.module').warning('Testing for SO')

给我:

2010-06-07 08:43:10,494 WARNING this.is.the.module 14980/MainThread: Testing for SO

这篇关于python中的记录器链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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