分享一个python记录多日志文件的代码

 开发  python   2017-05-18 20:54   评论次 

先上代码吧。

#!/usr/bin/python
#coding=utf-8

import logging, logging.handlers
import sys
import os
GLOBAL={"LogLevel": "WARNNING"}

class Logger: 

    def __init__(self, logName, backupCount=10):
        self.logName = logName
        self.log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'logs')
        self.logFile = os.path.join(self.log_dir, '{0}.log'.format(self.logName))
        self._levels = {
            "DEBUG" : logging.DEBUG,
            "INFO" : logging.INFO,
            "WARNING" : logging.WARNING,
            "ERROR" : logging.ERROR,
            "CRITICAL" : logging.CRITICAL
        }
        self._logfmt = '%Y-%m-%d %H:%M:%S'
        self._logger = logging.getLogger(self.logName)
        if not os.path.exists(self.log_dir): os.mkdir(self.log_dir)

        handler = logging.handlers.TimedRotatingFileHandler(filename=self.logFile,
                              backupCount=backupCount,
                              when="midnight")
        handler.suffix = "%Y%m%d"
        formatter = logging.Formatter('[ %(levelname)s ] %(asctime)s %(filename)s:%(threadName)s:%(lineno)d %(message)s', datefmt=self._logfmt)
        handler.setFormatter(formatter)
        self._logger.addHandler(handler)
        self._logger.setLevel(self._levels.get(GLOBAL.get('LogLevel')))

    @property
    def getLogger(self):
        return self._logger

if __name__ == "__main__":
        syslog = Logger("sys").getLogger
        reqlog = Logger("req").getLogger

        syslog.info("sys hello info")
        syslog.debug("sys hello debug")
        syslog.error("sys hello error")
        syslog.warning("sys hello warning")

        reqlog.info("req hello info")
        reqlog.debug("req hello debug")
        reqlog.error("req hello error")
        reqlog.warning("req hello warning")


点赞 打赏
取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

交流分享

QQ扫一扫或点击二维码加入,群号577543189
微信扫一扫,手滑关注它
微信扫一扫,进入小程序

推荐文章

标签云集

友情链接  交换友链

推广位