網站首頁 編程語言 正文
參考官方案例: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)
原文鏈接:https://www.cnblogs.com/OnlyDreams/p/15923001.html
相關推薦
- 2022-08-19 python?return實現匯率轉換器教程示例_python
- 2022-05-20 Redis 做接口限流,一個注解的事
- 2022-04-14 解決Goland錯誤:$GOPATH/go.mod exists but should not
- 2023-04-01 Pytorch中關于F.normalize計算理解_python
- 2022-06-06 layui 日期格式不正確(date、datetime)區別
- 2022-05-24 C#多線程TPL模式下使用HttpClient_C#教程
- 2022-07-06 R語言可視化開發forestplot根據分組設置不同顏色_R語言
- 2022-11-16 Python數據分析之matplotlib繪圖詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支