简体   繁体   English

python logger多线程类

[英]python logger class for multithreading

I'm using my own logger class in my freelance projects for access a logs via ftp and check errors. 我在自由项目中使用自己的记录器类,以通过ftp访问日志并检查错误。 It writes a separate file for each process which output to stdout via os.getpid() function. 它为每个进程编写一个单独的文件,该文件通过os.getpid()函数输出到stdout。 This is useful for python multiprocess library. 这对于python多进程库很有用。 But I'm doing multithreading more often than multiprocessing and I don't know how to improve my code to write a separate file for each thread which outputes to stdout. 但是我比多处理更多地使用多线程,而且我不知道如何改进我的代码以为输出到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()

How to do that? 怎么做?

If the same strategy is used, logging a separate log file for each worker, then there has to be some sort of identifier for each thread. 如果使用相同的策略,为每个工作程序记录一个单独的日志文件,则每个线程必须有某种标识符。 Since each thread is executed in the same process they will all have the same process id. 由于每个线程在同一进程中执行,因此它们都将具有相同的进程ID。

I believe you could use the thread ident to identify it: 我相信您可以使用线程标识来标识它:

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

A threading aware logger might be able to create a unique identifier with: 线程感知记录器可能能够使用以下方法创建唯一标识符:

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

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

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