python:打印每个线程的输出以分隔文件,无进程 [英] python : print output of each thread to seperate file no processes

查看:127
本文介绍了python:打印每个线程的输出以分隔文件,无进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个线程,每个线程将输出写入stdout.但是,我想将每个线程的输出重定向到彼此独立的单独文件中,然后将它们合并以保持每个线程的流动.

I have several threads and each thread writes output to stdout. However I want to redirect the ouput of each thread to a separate file independently of each other, then merge them to keep he flow of each thread together.

我的意思是:

Thread1将每个打印,每个异常和其他输出写入到file1.log中 Thread2将每个打印,每个异常和每个其他输出写入file2.log 等等. 所以我要寻找的是排他地设置每个线程的标准输出.但是,设置stdout仅在全局范围内起作用,这意味着Thread1和Tread2将始终写入同一已定义的stdout.我还没有找到如何做到这一点. 我不能使用进程,因为还有另一个问题.

Thread1 writes every print, every exception and every other ouput into file1.log Thread2 writes every print, every exception and every other ouput into file2.log and so on. So what I'm looking for is to set the stdout for each thread exclusivly. However setting the stdout only works globally mean that Thread1 and Tread2 will always write to the same defined stdout. I have not found out yet how to do this. I can't use processes though, because f another issue.

我该怎么做?

推荐答案

Python logging 模块为线程安全.

The Python logging module is thread-safe.

使用它为每个线程创建一个单独的记录器,并注册

Use it to create an individual logger for each thread, and register a FileHandler to (also) log to a file:

logger = logging.getLogger('thread-1')
file_handler = logging.FileHandler('thread-1.log')
logger.addHandler(file_handler)

这是一个更完整的示例:

Here's a more complete example:

import logging
import random
import threading
import time

NUM_THREADS = 5


def worker(delay, logger):
    """A toy worker function, taking the logger as an argument.
    """
    logger.info("Starting work...")
    for i in range(3):
        logger.info('Sleeping %0.02f', delay)
        time.sleep(delay)
    logger.info('Done.')


for n in range(1, NUM_THREADS + 1):
    # create the thread's logger
    logger = logging.getLogger('thread-%s' % n)
    logger.setLevel(logging.DEBUG)

    # create a file handler writing to a file named after the thread
    file_handler = logging.FileHandler('thread-%s.log' % n)

    # create a custom formatter and register it for the file handler
    formatter = logging.Formatter('(%(threadName)-10s) %(message)s')
    file_handler.setFormatter(formatter)

    # register the file handler for the thread-specific logger
    logger.addHandler(file_handler)

    delay = random.random()
    t = threading.Thread(target=worker, args=(delay, logger))
    t.start()


main_thread = threading.currentThread()
for t in threading.enumerate():
    if t is not main_thread:
        t.join()

这将为您提供五个日志文件,从thread-1.logthread-5.log,仅包含相应线程的输出:

This will give you five logfiles, thread-1.log through thread-5.log, containing only the output of the respective thread:

thread-1.log

thread-1.log

(Thread-1  ) Starting work...
(Thread-1  ) Sleeping 0.53
(Thread-1  ) Sleeping 0.53
(Thread-1  ) Sleeping 0.53
(Thread-1  ) Done.


如果您仍要登录到控制台,只需创建一个 StreamHandler 并将其附加到您的记录器:


If you still want to log to the console, simply create a StreamHandler and attach it to your logger:

stream_handler = logging.StreamHandler()
logger.addHandler(stream_handler)

这将默认登录到STDERR.如果要STDOUT,请使用

This will log to STDERR by default. If you want STDOUT, use

logging.StreamHandler(sys.stdout)

有关使用Python logging模块的更多信息,请参见

For more information on using the Python logging module, see the Advanced Logging Tutorial.

这篇关于python:打印每个线程的输出以分隔文件,无进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆