python logging模块的多文件应用

概述

有的时候需要在一个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
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值