Python logging 封装

# -*- coding: utf-8 -*-
import inspect
import time
import os
import logging

current_path = os.path.dirname(__file__)
current_log_path = os.path.join(current_path, 'logs')


class LogUtils:

    def __init__(self, log_name=None, log_path=None):
        """
        通过python自带的logging模块进行封装
        :param log_name: 日志文件名
        :param log_path: 日志路径
        """
        # inspect.stack() 用于获取当前调用栈的信息, 获取调用logging程序名字
        caller_filename = inspect.stack()[1].filename.split('\\')[-1]
        self.log_name = log_name if log_name else caller_filename

        # 路径为空时设置为当前项目下
        self.logfile_path = log_path if log_path else current_log_path

        if not os.path.exists(self.logfile_path):
            os.makedirs(self.logfile_path)

        # 创建日志对象logger
        self.logger = logging.getLogger(__name__)
        # 设置日志级别
        self.logger.setLevel(level=logging.INFO)
        # 设置日志的格式
        formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s\n')

        """在log文件中输出日志"""
        # 日志文件名称显示一天的日志
        self.log_name_path = os.path.join(self.logfile_path, "%s_%s" % (self.log_name, time.strftime('%Y_%m_%d')+".log"))
        # 创建文件处理程序并实现追加
        self.file_log = logging.FileHandler(self.log_name_path, 'a', encoding='utf-8')
        # 设置日志文件里的格式
        self.file_log.setFormatter(formatter)
        # 设置日志文件里的级别
        self.file_log.setLevel(logging.INFO)
        # 把日志信息输出到文件中
        self.logger.addHandler(self.file_log)
        # 关闭文件
        self.file_log.close()

        """在控制台输出日志"""
        # 日志在控制台
        self.console = logging.StreamHandler()
        # 设置日志级别
        self.console.setLevel(logging.INFO)
        # 设置日志格式
        self.console.setFormatter(formatter)
        # 把日志信息输出到控制台
        self.logger.addHandler(self.console)
        # 关闭控制台日志
        self.console.close()

    def get_log(self):
        return self.logger


if __name__ == '__main__':
    logger = LogUtils().get_log()
    logger.info('123')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值