gpt4 book ai didi

python - 在 python 日志记录中显示线程 native_id

转载 作者:行者123 更新时间:2023-12-04 07:30:11 25 4
gpt4 key购买 nike

有没有办法显示线程native_id:

native_id

The native integral thread ID of this thread. This is a non-negative integer, orNone if the thread has not been started. Seethe get_native_id() function. This represents the Thread ID (TID) asassigned to the thread by the OS (kernel). Its value may be used touniquely identify this particular thread system-wide (until the threadterminates, after which the value may be recycled by the OS).


在 python 日志中使用日志记录 LogRecord attributes .
%(threadName)s 和 %(thread)s 不显示 native_id。
我正在使用 linux Ubuntu 和 RHEL。
谢谢

最佳答案

您可以添加一个过滤器功能来拦截日志消息并向其中添加线程 id

In [1]: import threading

In [2]: def thread_id_filter(record):
...: """Inject thread_id to log records"""
...: record.thread_id = threading.get_native_id()
...: return record
...:

In [3]: import logging

In [4]: my_logger = logging.getLogger()

In [5]: handler = logging.StreamHandler()

In [6]: handler.setFormatter(logging.Formatter('%(asctime)s | %(levelname)s | %(thread_id)s | %(message)s'))

In [7]: handler.addFilter(thread_id_filter)

In [8]: my_logger.addHandler(handler)

In [9]: my_logger.setLevel('INFO')

In [10]: my_logger.info('test123')
2021-06-15 18:33:20,400 | INFO | 6795172 | test123

关于python - 在 python 日志记录中显示线程 native_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67989173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com