1、用yaml配置文件来配置logging日志 2、以当前日期(ex.年月日时分)作为日志文件名
代码目录结构如下:
py
|-- config
|--config.yaml
|--logger.py
version: 1
disable_existing_loggers: False
formatters:
simple:
format: '[%(asctime)s] [%(levelname)s] %(message)s'
upgrade:
format: "[%(asctime)s] [%(filename)s] [Pid:%(process)d] [%(levelname)s] %(message)s"
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
file_handler:
class: logging.handlers.RotatingFileHandler
level: DEBUG
formatter: upgrade
filename: ./logs/all_log.log
maxBytes: 10485760
backupCount: 50
encoding: utf8
root:
level: DEBUG
handlers: [console, file_handler]
import logging
import os.path
import time
import yaml
import logging.config
project_path = 'py'
class Logger(object):
def __init__(self):
current_path=os.path.dirname(os.path.abspath(project_path))
path1=current_path.split(project_path)
path2=[path1[0], project_path]
log_path=''.join(path2) + '/logs/'
config_path=''.join(path2) + '/config/config.yaml'
dir_time = time.strftime('%Y%m%d', time.localtime(time.time()))
current_time=time.strftime('%Y%m%d%H%M',time.localtime(time.time() ))
log_name = log_path + dir_time + '/' + current_time + '.log'
if not os.path.exists(log_path + dir_time):
os.makedirs(log_path + dir_time)
try:
with open(file=config_path, mode='r', encoding="utf-8")as file:
logging_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)
logging_yaml['handlers']['file_handler']['filename'] = log_name
logging.config.dictConfig(config=logging_yaml)
self.log = logging.getLogger()
except Exception as e:
print(e)
def debug(cls, msg):
cls.log.debug(msg)
return
def info(cls,msg):
cls.log.info(msg)
return
def error(cls, msg):
cls.log.error(msg)
return
if __name__ == '__main__':
logger = Logger()
logger.info('This is info')
logger.debug('This is debug')
logger.error('This is error')
运行代码:
参考链接
1.https://www.cnblogs.com/yfacesclub/p/10396011.html 2.https://blog.csdn.net/TracelessLe/article/details/108887001
|