#脚本
#py文件
import logging
from configparser import ConfigParser
import os,time
class Homework():
def __init__(self,file_path= "Section.cfg",section = "config_homework",Level_option = "level",Format_option = "FORMAT",encoding = "UTF-8"):
"""
默认初始化读取配置文件
:param file_path:
:param encoding:
"""
self.cf = ConfigParser()
self.cf.read(file_path,encoding)
self.Level = self.cf.get(section, Level_option)
self.fm = logging.Formatter(self.cf.get(section,Format_option))
def log_homework(self,logger = "My_Logs"):
"""
log文件创建及读取
:return:
"""
#创建日志文件并设定收集信息级别
my_logger = logging.getLogger(logger)
my_logger.setLevel(self.Level)
#编辑日志格式并设定输出信息级别
ch = logging.StreamHandler()
ch.setLevel(self.Level)
ch.setFormatter(self.fm)
#指定输出到文本渠道
fh = logging.FileHandler(logger,encoding="UTF-8")
fh.setLevel(self.Level)
fh.setFormatter(self.fm)
#渠道
my_logger.addHandler(ch)
my_logger.addHandler(fh)
#收集日志
my_logger.debug(‘this is a debug level message‘)
my_logger.info(‘this is info level message‘)
my_logger.warning(‘this is warning level message‘)
my_logger.error(‘this is error level message‘)
my_logger.critical(‘this is critical level message‘)
if __name__ == ‘__main__‘:
hw = Homework()
hw.log_homework()
#配置文本(cfg文件) [config_homework] level=DEBUG FORMAT = ‘%%(asctime)s : %%(levelname)s : %%(message)s‘
输出结果:
2019-03-20 11:44:38,134 : DEBUG : this is a debug level message 2019-03-20 11:44:38,134 : INFO : this is info level message 2019-03-20 11:44:38,135 : WARNING : this is warning level message 2019-03-20 11:44:38,135 : ERROR : this is error level message 2019-03-20 11:44:38,135 : CRITICAL : this is critical level message 2019-03-20 11:48:03,167 : DEBUG : this is a debug level message 2019-03-20 11:48:03,168 : INFO : this is info level message 2019-03-20 11:48:03,168 : WARNING : this is warning level message 2019-03-20 11:48:03,168 : ERROR : this is error level message 2019-03-20 11:48:03,168 : CRITICAL : this is critical level message
这是一个初级的自定义日志类,只不过和配置文件关联起来了,初始化读取配置文件,然后基础的输出log日志及打印
注意点:
1.决定好需要初始化的参数,像这个文件,因为要读取配置文件中的参数来定义信息等级和输出格式,所以最好初始化读取的方法
2.因为log的输出格式涉及到%所以转义字符时必须的
3.尽量模块化方法,提高代码的可重复利用性,只不过常用默认参数而不是main方法传参是我个人习惯
原文:https://www.cnblogs.com/keima/p/10564081.html