在多线程中将logging.info
输出到不同的文件中,可以使用Python标准库中的Queue
和Thread
模块。具体实现步骤如下:
Queue
队列用于不同线程的日志输出,每个队列对应一个日志文件。import queue
# 创建三个队列用于不同线程的日志输出
log_q1 = queue.Queue()
log_q2 = queue.Queue()
log_q3 = queue.Queue()
Handler
对象,分别处理不同的队列,并设置不同的输出格式和日志级别。import logging
# 配置日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 定义输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 创建三个handler,分别处理不同的队列
handler1 = logging.FileHandler("log1.txt")
handler1.setFormatter(formatter)
handler1.setLevel(logging.ERROR)
handler1.setStream(log_q1)
handler2 = logging.FileHandler("log2.txt")
handler2.setFormatter(formatter)
handler2.setLevel(logging.WARNING)
handler2.setStream(log_q2)
handler3 = logging.FileHandler("log3.txt")
handler3.setFormatter(formatter)
handler3.setLevel(logging.INFO)
handler3.setStream(log_q3)
# 将三个handler添加到logger中
logger.addHandler(handler1)
logger.addHandler(handler2)
logger.addHandler(handler3)
import threading
def worker1():
while True:
try:
record = log_q1.get()
if record is None:
break
logger.handle(record)
except Exception:
pass
def worker2():
while True:
try:
record = log_q2.get()
if record is None:
break
logger.handle(record)
except Exception:
pass
def worker3():
while True:
try:
record = log_q3.get()
if record is None:
break
logger.handle(record)
except Exception:
pass
t1 = threading.Thread(target=worker1)
t1.start()
t2 = threading.Thread(target=worker2)
t2.start()
t3 = threading.Thread(target=worker3)
t3.start()
logging.info
等函数输出日志,将日志信息放入相应的队列中即可。# 在主线程中使用logging.info等函数输出日志,将日志信息放入相应的队列中
log_q1.put(logging.makeRecord("logger1", logging.ERROR, "test message", (), None, None, None))
log_q2.put(logging.makeRecord("logger2", logging.WARNING, "test message", (), None, None, None))
log_q3.put(logging.makeRecord("logger3", logging.INFO, "test message", (), None, None, None))
通过以上步骤,即可实现多线程中将logging.info
输出到不同的文件中。需要注意的是,在使用Queue
传递日志信息时,需要使用logging.makeRecord()
方法创建LogRecord
对象,并指定相应的logger名称、日志级别、消息内容等信息。