繁体   English   中英

python logger多线程类

[英]python logger class for multithreading

我在自由项目中使用自己的记录器类,以通过ftp访问日志并检查错误。 它为每个进程编写一个单独的文件,该文件通过os.getpid()函数输出到stdout。 这对于python多进程库很有用。 但是我比多处理更多地使用多线程,而且我不知道如何改进我的代码以为输出到stdout的每个线程编写一个单独的文件。

class Logger(object):
    def __init__(self, realstdout, path='logs/'):
        today = datetime.datetime.now().isoformat()
        if path[-1] != '/':
            path = path+'/'
        os.mkdir(path + today)

        self.pid = str(os.getpid())
        self.handler = open(path + today + '/' + self.pid + '.txt', 'w', buffering=0)
        self.stdout = realstdout

    def write(self, buf):
        if buf == '\n' or buf == '(Pdb)':
            return
        buf = buf.replace('\n', '#')
        self.handler.write("[{0}]  [{1}] ".format(datetime.datetime.today(), self.pid) + buf + "\n")
        self.stdout.write("[{0}] ".format(self.pid) + buf + "\n")

    def flush(self):
        pass

    def __del__(self):
        self.handler.close()

怎么做?

如果使用相同的策略,为每个工作程序记录一个单独的日志文件,则每个线程必须有某种标识符。 由于每个线程在同一进程中执行,因此它们都将具有相同的进程ID。

我相信您可以使用线程标识来标识它:

>>> threading.current_thread()
<_MainThread(MainThread, started 139944996378368)>
>>> threading.current_thread().ident
139944996378368

线程感知记录器可能能够使用以下方法创建唯一标识符:

self.pid = str(threading.current_thread().ident)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM