python - 将字符串添加到线程名称末尾

标签 python python-3.x python-multithreading

我正在使用日志记录模块打印一些数据。这是我的代码:

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/

相关文章:

python - python是否支持多处理器/多核编程?

python - 打印字符映射

python - 错误 : The 'elasticsearch' backend requires the installation of 'requests' . 如何修复?

php - int((0.1+0.7)*10) = 7 在多种语言中。如何防止这种情况?

python - 在Python中修改特定索引处的多维数组

python - 汉诺塔非递归函数

python - 如何设计我的 python 应用程序以跨多核并行工作

python - 考虑到 GIL,asyncio 怎么可能不是线程安全的?

Python:在列表中存储和删除线程

python - scipy interpolate 给出无界值