需求:
针对不同的项目按照年月生成不同的日志目录。
import os,datetime,logging,logging.config
from core.config.config_log import *
from core.kernel.exception import *
class Log:
def __init__(self):
logging.config.dictConfig(LOG_CONFIG)
self.logger = logging.getLogger("system")
def get_logger(self):
return self.logger
def create_handler(self,level,file_name):
handler = logging.handlers.RotatingFileHandler(file_name,"a", maxBytes=0, backupCount=0, delay=False)
handler.setLevel(level)
handler.setFormatter(logging.Formatter(LOG_CONFIG["formatters"]["standard"]["format"]))
return handler
def create_filter(self):pass
def create_project_logger(self,project=None):
if project:
direct =LOG_PATH + project + "/" + str(TODAY_TIME.year) + "/" + str(TODAY_TIME.month)
if not os.path.exists(direct):
self.logger.info("创建文件夹,directName: %s",direct)
os.makedirs(direct)
if not os.path.exists(direct):
self.logger.error("创建文件夹失败,directName %s",direct)
raise MyException(-1,"创建日志文件夹失败")
self.logger.addHandler(self.create_handler(logging.INFO,direct+"/info_" +str(datetime.datetime.now().date())+".log"))
self.logger.addHandler(self.create_handler(logging.ERROR,direct+"/error_" +str(datetime.datetime.now().date())+".log"))
# not work
self.logger.removeHandler(self.create_handler(logging.INFO,LOG_PATH + "/system.log"))
return self.logger
LOG = Log().get_logger()
配置文件:config_log.py
import datetime
LOG_PATH = './log/'
TODAY_TIME = datetime.datetime.now()
LOG_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '[%(asctime)s][%(levelname)s]-%(message)s'
}
},
'filters': {
},
'handlers': {
'system': {
'level':'INFO',
'class':'logging.handlers.RotatingFileHandler',
'filename': LOG_PATH + "/system.log",
'maxBytes': 1024*1024*5, # 5 MB
'backupCount': 5,
'formatter':'standard',
'mode':'a',
},
'console':{
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'system':{
'handlers': ['system','console'],
'level':"INFO",
'propagate': False
},
}
}