https://blog.csdn.net/weixin_45912307/article/details/109519430
书写方式1
# -*- coding: utf-8 -*-
# @Time : 2020/11/15 20:03
# @Author : jsonLiu
# @Email : xxxxx
# @File : logger.py
import logging
class Logger:
def logger(self, level, msg):
# 1.定义一个日志收集器
logger = logging.getLogger()
# 2. 设置级别
logger.setLevel("DEBUG")
# 3. 设置输出格式
formatter = logging.Formatter('%(asctime)s-%(levelname)s-%(filename)s-%(name)s-日志信息:%(message)s')
# 4. 创建一个输出渠道
ch = logging.StreamHandler() # 输出到控制台
ch.setLevel("DEBUG")
ch.setFormatter(formatter)
fh = logging.FileHandler('test.txt', encoding='UTF-8') # 输出到文件
fh.setLevel("ERROR")
fh.setFormatter(formatter)
# 5. 两者对接---指定输出渠道
logger.addHandler(ch)
logger.addHandler(fh)
# 6. 收集日志
if level == "DEBUG":
logger.debug(msg)
elif level == "INFO":
logger.info(msg)
elif level == "WARNING":
logger.warning(msg)
elif level == "ERROR":
logger.error(msg)
elif level == "CRITICAL":
logger.critical(msg)
# 7. 关闭渠道
logger.removeHandler(ch)
logger.removeHandler(fh)
def debug(self, msg):
self.logger("DEBUG",msg)
def info(self, msg):
self.logger("INFO",msg)
def warning(self, msg):
self.logger("WARNING",msg)
def error(self, msg):
self.logger("ERROR",msg)
def critical(self, msg):
self.logger("CRITICAL",msg)
if __name__ == '__main__':
logger = Logger()
logger.debug('debug级别信息!')
logger.info('info级别的信息')
logger.warning('warning级别信息')
logger.error('error级别信息!')
logger.critical('critical级别信息!')
源码:
输出结果:
书写方式2
# -- encoding: utf-8 --
# @time: 2020/11/29 22:13
# @Author: jsonLiu
# @Email: xxxxxx@qq.com
# @file: logger_handler.py
import logging
from logging import Logger
import os
class LoggerHandler(Logger):
def __init__(self,
name='py_api_test_v1.0',
level = 'DEBUG',
FileHandler_level = 'ERROR',
console_level = 'INFO',
format = '%(asctime)s-%(filename)s-%(lineno)d-%(name)s-%(levelname)s-日志信息:%(message)s',
file = None):
# 初始化收集器
# logger = logging.getLogger(name)
super().__init__(name)
# 设置收集器级别
self.setLevel(level)
# 设置日志格式
formatter = logging.Formatter(format)
# 初始化处理器
if file:
fh = logging.FileHandler(file,encoding='UTF-8')
# 设置handler级别
fh.setLevel(FileHandler_level)
# 设置处理器输出格式 file_handler.setFormatter(fmt)
fh.setFormatter(formatter)
# 添加处理器 addHandler
self.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(console_level)
ch.setFormatter(formatter)
self.addHandler(ch)
# parent_path = os.path.dirname(os.path.abspath(__file__))
# logs_path = os.path.join(parent_path,'logs')
base_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]
logs_path = os.path.join(base_path,'logs')
# print(base_path)
if not os.path.exists(logs_path):
os.mkdir(logs_path)
file_name = 'api_test_log.txt'
logs_file = os.path.join(logs_path,file_name)
logger = LoggerHandler(file=logs_file)
if __name__ == '__main__':
logger = LoggerHandler()
info_msg = 'info级别信息'
error_msg = 'error错误信息'
logger.error(error_msg)
logger.info(info_msg)
方式2的调用
from logger_handler import logger
msg = 'msg级别信息'
logger.error(msg)