python?logging多進(jìn)程多線程輸出到同一個日志文件的實(shí)戰(zhàn)案例
參考官方案例: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()
實(shí)戰(zhàn)案例:
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、主進(jìn)程中開啟獨(dú)立的日志寫入監(jiān)聽線程
"""主進(jìn)程中開啟獨(dú)立的日志寫入監(jiān)聽線程""" 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()
日志寫入函數(shù)
def logger_main(q): '''日志隊(duì)列寫入文件''' while True: record = q.get() if record is None: break logger = logging.getLogger() logger.handle(record)
3、子進(jìn)程中將日志輸入QueueHandler日志隊(duì)列
def child_proc_main(queue): lqh = logging.handlers.QueueHandler(queue) lqh.set_name("my_queue_handler") root = logging.getLogger() #很關(guān)鍵的一步,必須先清空,再加入。原因:多進(jìn)程多線程復(fù)雜環(huán)境下,在window和linux平臺運(yùn)行表現(xiàn)不一致,linux會復(fù)制主進(jìn)程的日志配置,造成同時輸出多個日志文件。 root.handlers.clear() root.addHandler(lqh) root.setLevel(level)
到此這篇關(guān)于python logging多進(jìn)程多線程輸出到同一個日志文件的文章就介紹到這了,更多相關(guān)python logging日志文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python django 增刪改查操作 數(shù)據(jù)庫Mysql
下面小編就為大家?guī)硪黄猵ython django 增刪改查操作 數(shù)據(jù)庫Mysql。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換)
本文主要介紹了PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Python解析命令行讀取參數(shù)之a(chǎn)rgparse模塊
這篇文章主要介紹了Python解析命令行讀取參數(shù)之a(chǎn)rgparse模塊,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07python實(shí)現(xiàn)一行輸入多個值和一行輸出多個值的例子
今天小編就為大家分享一篇python實(shí)現(xiàn)一行輸入多個值和一行輸出多個值的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07python數(shù)學(xué)建模之Matplotlib?實(shí)現(xiàn)圖片繪制
這篇文章主要介紹了python數(shù)學(xué)建模之Matplotlib?實(shí)現(xiàn)圖片繪制,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07Python實(shí)現(xiàn)基于socket的udp傳輸與接收功能詳解
這篇文章主要介紹了Python實(shí)現(xiàn)基于socket的udp傳輸與接收功能,結(jié)合實(shí)例形式詳細(xì)分析了Python使用socket進(jìn)行udp文件傳輸與接收相關(guān)操作技巧及注意事項(xiàng),需要的朋友可以參考下2019-11-11Python3+Django get/post請求實(shí)現(xiàn)教程詳解
這篇文章主要介紹了Python3+Django get/post請求實(shí)現(xiàn)教程詳解,需要的朋友可以參考下2021-02-02打印出python 當(dāng)前全局變量和入口參數(shù)的所有屬性
打印出python 當(dāng)前全局變量和入口參數(shù)的所有屬性的實(shí)現(xiàn)代碼。2009-07-07