python日志模块的使用

这就是一个SpiderHelper.py文件

import os
import time
import logging
from logging import handlers


# 日志工具
class LogGer:
    def __init__(self, name):
        os.makedirs("./log") if not os.path.exists("./log") else None  # 创建日志文件文件夹
        GetLoggerA = logging.getLogger()
        GetLoggerA.setLevel(logging.INFO)  # 设置默认级别
        formatter = logging.Formatter('%(levelname)s %(asctime)s %(filename)s[line:%(lineno)d]: %(message)s')
        log_file_path = './log/{}_{}.log'.format(name, time.strftime('%Y%m%d'))
        RotatingHandler = handlers.RotatingFileHandler(
            log_file_path, maxBytes=20 * 1024 * 1024, backupCount=10, encoding='utf-8')
        RotatingHandler.setFormatter(formatter)

        GetLoggerA.addHandler(RotatingHandler)
        StreamHandler = logging.StreamHandler()
        StreamHandler.setFormatter(formatter)
        GetLoggerA.addHandler(StreamHandler)
        # 过滤级别:控制台输出INFO和WARNING级别,文件只记录WARNING级别
        info_filter = logging.Filter()
        info_filter.filter = lambda record: record.levelno < logging.WARNING  # 设置过滤等级
        warn_filter = logging.Filter()
        warn_filter.filter = lambda record: record.levelno >= logging.WARNING
        # streamHandler.addFilter(info_filter)
        RotatingHandler.addFilter(warn_filter)

那么我们如何使用呢?

import os
import logging
import SpiderHelper


class SpiderDemo:
    SpiderHelper.LogGer(str(os.path.basename(__file__))[:-3])

    def __init__(self):
       logging.info('这是日志消息')
       logging.warning('这是警告日志')

Robin.Liu

三千大千世界,即非世界,是名世界

友情链接

苏ICP备18038860号

Copyright © sogemao.com 版权所有 Robin.Liu