更新时间:2021-07-20 23:20:50
是的,您可以将日志条目从不同的线程定向到不同的文件.您需要:
Yes, you can direct log entries from different threads to different files. You'll need to:
LogRecord.thread
或 LogRecord.threadName
属性 LogRecord.thread
or LogRecord.threadName
attribute过滤时,您可以选择过滤线程ID(由 threading.get_ident()
)或线程名称(无论您以 name
作为参数传递给
When filtering, you have the choice between filtering on thread id (the value returned by threading.get_ident()
) or thread name (whatever you passed in as the name
argument to the Thread()
object). If you have a pattern for your thread names, this is where you'd use it.
创建自定义过滤器非常简单:
Creating a custom filter is easy enough:
import threading
from logging import Filter
class ThreadFilter(Filter):
"""Only accept log records from a specific thread or thread name"""
def __init__(self, threadid=None, threadname=None):
if threadid is None and threadname is None:
raise ValueError("Must set at a threadid and/or threadname to filter on")
self._threadid = threadid
self._threadname = threadname
def filter(self, record):
if self._threadid is not None and record.thread != self._threadid:
return False
if self._threadname is not None and record.threadName != self._threadname:
return False
return True
class IgnoreThreadsFilter(Filter):
"""Only accepts log records that originated from the main thread"""
def __init__(self):
self._main_thread_id = threading.main_thread().ident
def filter(self, record):
return record.thread == self._main_thread_id
如果要匹配特定的模式,请相应地调整代码.
If you want to match a specific pattern, adjust the code accordingly.