示例代码
# 导入日志模块
import logging
import logging.config
from config import LOG_DIR, settings
def config_logging(): # 定义日志配置方法
config_dict = { # 定义日志配置字典
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'debug_fmt': {'format': '%(asctime)s %(pathname)s:%(lineno)d @%(funcName)s %(levelname)s: %(message)s'},
'test_name': {'format': '%(asctime)s %(pathname)s:%(lineno)d %(name)s @%(funcName)s %(levelname)s: %(message)s'},
'verbose': {'format': '%(asctime)s %(levelname)s %(name)s %(process)d %(thread)d %(message)s'},
},
'handlers': { # 定义'handlers', 这里有三个handlers-> [Stream, debug_file, info_file]
"Stream": {
"formatter": 'debug_fmt',
'level': 'DEBUG',
"class": "logging.StreamHandler",
},
"debug_file": {
"formatter": 'debug_fmt',
"level": 'DEBUG',
"class": 'logging.handlers.TimedRotatingFileHandler',
"filename": LOG_DIR / 'debug.log',
"backupCount": 1,
"when": 'D',
"encoding": 'utf-8',
},
"info_file": {
"formatter": 'debug_fmt',
"level": 'INFO',
"class": 'logging.handlers.TimedRotatingFileHandler',
"filename": LOG_DIR / 'info.log',
"backupCount": 3,
"when": 'D',
"encoding": 'utf-8',
},
},
'loggers': { # 定义loggers
'': {'level': settings.LOG_LEVEL, 'handlers': settings.LOG_HANDLERS}, # 使用了dynaconf模块调用config配置, level可以传入DEBUG、INFO等, handlersk可以传入字典中定义的handlers
},
}
logging.config.dictConfig(config_dict) # 使用dictConfig方法,传入字典格式的日志配置
config_logging()
logger = logging.getLogger('msp_log') # 实例化log对象为logger, 后续调用可以用logger.info('msg')
if __name__ == '__main__':
def how(a, *args, **kwargs):
logger.debug('debug')
logger.info('info')
logger.info(LOG_DIR)
logger.info(f'{a, *args}')
return 'hello'
how(2, [12, 34], {'aaaa': 'aaaa', 'bb': 'bb'}, c='c', d='d')
返回
2024-01-29 15:04:00,836 d:\My\crmProjects\utils\log_setting.py:56 @how DEBUG: debug
2024-01-29 15:04:00,837 d:\My\crmProjects\utils\log_setting.py:57 @how INFO: info
2024-01-29 15:04:00,837 d:\My\crmProjects\utils\log_setting.py:58 @how INFO: D:\My\crmProjects\files\logs
2024-01-29 15:04:00,838 d:\My\crmProjects\utils\log_setting.py:59 @how INFO: (2, [12, 34], {'aaaa': 'aaaa', 'bb': 'bb'})
标签:info,logging,log,python,debug,日志,config,logger
From: https://www.cnblogs.com/ishuangjin/p/17994595