之前使用的是logging模块,后添加color formatter
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@desc:
@author:
@software: PyCharm on 2018/8/21
"""
import logging
import os
import time
from logging import config
from logging.handlers import RotatingFileHandler
import yaml
from colorlog import colorlog
class FinalLogger:
def __init__(self):
file_path = os.path.abspath(os.path.dirname(__file__))
self.logging_config_path = os.path.join(file_path, "../conf/logging_config.yaml")
self._log_path = os.path.join(file_path, "../" + "logs")
if not os.path.exists(self._log_path):
os.makedirs(self._log_path)
with open(self.logging_config_path, encoding="utf-8") as f:
log_config = yaml.load(f.read())
log_config["handlers"]["info_file_handler"]["filename"] = \
os.path.join(self._log_path, log_config["handlers"]["info_file_handler"]["filename"])
logging.config.dictConfig(log_config)
@classmethod
def get_logger(cls):
"""
:return: 返回logger句柄
"""
logger = logging.getLogger()
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(asctime)s %(name)s %(filename)s:%(lineno)d [%(levelname)s]: %(message)s")
for hdr in logger.handlers:
if not isinstance(hdr, RotatingFileHandler):
hdr.formatter = formatter
return logger
logger = FinalLogger().get_logger()
del FinalLogger
if __name__ == "__main__":
logger.info("i am a err1!")
logger.error("i am a err2!")
yaml配置
version: 1
disable_existing_loggers: True
formatters:
simple:
format: "%(asctime)s %(name)s %(filename)s:%(lineno)d [%(levelname)s]: %(message)s"
datefmt: '%F %T'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: autotest.log #
maxBytes: 10485760 # 10MB
backupCount: 20 #most 20 extensions
encoding: utf8
root:
level: DEBUG
handlers: [console, info_file_handler]