首頁 > 軟體

python logging多程序多執行緒輸出到同一個紀錄檔檔案的實戰案例

2022-02-22 16:00:48

參考官方案例:https://docs.python.org/zh-cn/3.8/howto/logging-cookbook.html

import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue
import random
import threading
import time

def logger_thread(q):
    while True:
        record = q.get()
        if record is None:
            break
        logger = logging.getLogger(record.name)
        logger.handle(record)
def worker_process(q):
    qh = logging.handlers.QueueHandler(q)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(qh)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)
if __name__ == '__main__':
    q = Queue()
    d = {
        'version': 1,
        'formatters': {
            'detailed': {
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': 'INFO',
            },
            'file': {
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed',
            'foofile': {
                'filename': 'mplog-foo.log',
            'errors': {
                'filename': 'mplog-errors.log',
                'level': 'ERROR',
        'loggers': {
            'foo': {
                'handlers': ['foofile']
        'root': {
            'level': 'DEBUG',
            'handlers': ['console', 'file', 'errors']
    }
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
        workers.append(wp)
        wp.start()
    logging.config.dictConfig(d)
    lp = threading.Thread(target=logger_thread, args=(q,))
    lp.start()
    # At this point, the main process could do some useful work of its own
    # Once it's done that, it can wait for the workers to terminate...
    for wp in workers:
        wp.join()
    # And now tell the logging thread to finish up, too
    q.put(None)
    lp.join()

實戰案例:

1、字典形式設定紀錄檔

log_conf_dict = {
    'version': 1,
    'formatters': {
        'my_formatter': {
            'class': 'logging.Formatter',
            'format': '%(asctime)s %(processName)s(%(process)d) %(threadName)s(%(thread)d) %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'INFO',
            'formatter': 'my_formatter',
        },
        'file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/log/test.log',
            'maxBytes': 5*1024*1024,
            'backupCount': 60,
            'mode': 'w',
            'delay': True,
            'formatter': 'my_formatter',
            'encoding': 'utf-8',
            'level': 'INFO',
        },
    },
    'loggers': {
        'my_logger': {
            'handlers': ['file']
        }
    },
    'root': {
        'level': _level,
        'handlers': ['console', 'file']
    },
}

2、主程序中開啟獨立的紀錄檔寫入監聽執行緒

"""主程序中開啟獨立的紀錄檔寫入監聽執行緒"""
    queue = Queue(-1)
    logging.config.dictConfig(dict)
    log_thread = threading.Thread(target=logger_main, args=(queue,))
    log_thread.start()    """其他邏輯程式碼段"""    queue.put(None)    log_thread.join()

紀錄檔寫入函數

def logger_main(q):
'''紀錄檔佇列寫入檔案'''
    while True:
        record = q.get()
        if record is None:
            break
        logger = logging.getLogger()
        logger.handle(record)

3、子程序中將紀錄檔輸入QueueHandler紀錄檔佇列

def child_proc_main(queue):
    lqh = logging.handlers.QueueHandler(queue)
    lqh.set_name("my_queue_handler")
    
    root = logging.getLogger()    #很關鍵的一步,必須先清空,再加入。原因:多程序多執行緒複雜環境下,在window和linux平臺執行表現不一致,linux會複製主程序的紀錄檔設定,造成同時輸出多個紀錄檔檔案。
    root.handlers.clear()
    root.addHandler(lqh)
    root.setLevel(level)

到此這篇關於python logging多程序多執行緒輸出到同一個紀錄檔檔案的文章就介紹到這了,更多相關python logging紀錄檔檔案內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com