且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将消息从不同的线程记录到不同的文件?

更新时间: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 属性
  • 创建一个过滤器,该过滤器接受具有特定或所有线程ID的记录.
  • 为每个线程创建一个日志处理程序,为其提供一个日志过滤器,该过滤器仅接受特定线程的日志记录.
  • 将忽略线程日志记录的过滤器附加到任何其他处理程序.
  • Create a log filter that can filter records by their LogRecord.thread or LogRecord.threadName attribute
  • Create a filter that does not accept records with specific or all thread ids.
  • Create a log handler per thread, giving it a log filter that only accepts logrecords for their specific thread.
  • Attach the filter that ignores log records for your threads to any other handlers.

过滤时,您可以选择过滤线程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.