关闭

python logging模块的多文件应用

386438人阅读 评论(0) 收藏 举报
分类:

概述

有的时候需要在一个python程序中生成多个log文件。
本文对logging进一步封装,展示如何在一个程序中使用logging模块打印两个log文件来记录不同类型的信息。
注意logging模块是线程安全的,可以在多线程环境中使用。

完整的代码

#!/usr/bin/env python2.7
# -*- coding:utf-8 -*-
import logging, logging.handlers
class LogMgr:
    def __init__ (self, logpath, markpath):
        self.LOG = logging.getLogger('log')
        loghdlr1 = logging.handlers.RotatingFileHandler(logpath,"a", 0, 1)
        fmt1 = logging.Formatter("%(asctime)s %(threadName)-10s %(message)s", "%Y-%m-%d %H:%M:%S")
        loghdlr1.setFormatter(fmt1)
        self.LOG.addHandler(loghdlr1)
        self.LOG.setLevel(logging.INFO)

        self.MARK = logging.getLogger('mark')
        loghdlr2 = logging.handlers.RotatingFileHandler(markpath,"a", 0, 1)
        fmt2 = logging.Formatter("%(message)s")
        loghdlr2.setFormatter(fmt2)
        self.MARK.addHandler(loghdlr2)
        self.MARK.setLevel(logging.INFO)
    def error(self, msg):
        if self.LOG is not None:
            self.LOG.error(msg)
    def info(self, msg):
        if self.LOG is not None:
            self.LOG.info(msg)
    def debug(self, msg):
        if self.LOG is not None:
            self.LOG.debug(msg)
    def mark(self, msg):
        if self.MARK is not None:
            self.MARK.info(msg)
def main():
    global log_mgr
    log_mgr = LogMgr("mylog","mymark")  
    log_mgr.error('[mylog]This is error log')    
    log_mgr.info('[mylog]This is info log')    
    log_mgr.debug('[mylog]This is debug log')    
    log_mgr.mark('[mymark]This is mark log') 

if __name__ == "__main__":
    main()

执行结果


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1977930次
    • 积分:1133
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:1篇
    • 译文:1篇
    • 评论:0条
    文章分类