自定义封装Python3 logging模块实现全局灵活配置调用

2021年1月26日17:48:44 发表评论 2,199 ℃

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error() and critical()5个级别,但是内置的logging使用不够灵活,我们通过继承类重新封装logging,实现自定义logging模块。

# coding:utf-8
import logging,time,logging.handlers,os
class Log(object):
    def __init__(self, logger=None):
        # 创建一个logger
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)
        # 创建一个handler,用于写入日志文件
        self.logTime = time.strftime("%Y-%m-%d")
        self.logPath = os.path.abspath(os.path.join(os.path.dirname(__file__), './logs'))
        # 如果不存在这个logs文件夹,就自动创建一个
        if not os.path.exists(self.logPath):
            os.mkdir(self.logPath)
        # 日志文件的地址
        self.logName = self.logPath  + '/' + self.logTime + '.amd5.cn.log'
        # fh = logging.FileHandler(self.log_name, 'a')  # python2
        # fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')  # python3
        fh = logging.handlers.RotatingFileHandler(
            filename=self.logName,
            maxBytes=1024 * 1024 * 50,
            backupCount=5
        )
        fh.setLevel(logging.INFO)
        # 再创建一个handler,用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        # 定义handler的输出格式
        formatter = logging.Formatter(
            '[%(asctime)s] [%(filename)s]->%(funcName)s line:%(lineno)d [%(levelname)s]:%(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
  
        # 关闭打开的文件
        fh.close()
        ch.close()
    def MyLog(self):
        return self.logger
        
if __name__ == '__main__':
    log = Log().MyLog()
    def test1():
        log.info('阿汤博客')
    def test2():
        log.error('阿汤博客地址是:http://www.amd5.cn/')
    def test3():
        log.warning('阿汤博客地址是:http://www.amd5.cn/,欢迎访问!')
    test1()
    test2()
    test3()

其他页面调用:

from test import Log
log = Log().MyLog()
def test1():
    log.info('阿汤博客')
def test2():
    log.error('阿汤博客地址是:http://www.amd5.cn/')
def test3():
    log.warning('阿汤博客地址是:http://www.amd5.cn/,欢迎访问!')
test1()
test2()
test3()

日志输出效果:

[2021-01-26 17:45:29,943] [test.py]->test1 line:56 [INFO]:阿汤博客
[2021-01-26 17:45:29,943] [test.py]->test2 line:58 [ERROR]:阿汤博客地址是:http://www.amd5.cn/
[2021-01-26 17:45:29,944] [test.py]->test3 line:60 [WARNING]:阿汤博客地址是:http://www.amd5.cn/,欢迎访问!
[2021-01-26 17:45:52,539] [config.py]->test1 line:282 [INFO]:阿汤博客
[2021-01-26 17:45:52,539] [config.py]->test2 line:284 [ERROR]:阿汤博客地址是:http://www.amd5.cn/
[2021-01-26 17:45:52,539] [config.py]->test3 line:286 [WARNING]:阿汤博客地址是:http://www.amd5.cn/,欢迎访问!
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: