发布时间:2019-09-28 08:38:33编辑:auto阅读(2462)
官方文档:Logging HOWTO
官方文档:logging.config 模块
日志的等级(level)如下,只有大于等于配置的等级时,日志才会被记录。
# 默认等级为 WARNING NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL
官方模块有十几个 Handler(Useful Handlers),存在于 logging 和 logging.handlers 模块。常用的有:
logging.StreamHandler # 输出日志到控制台时使用(sys.stderr) logging.FileHandler # 输出日志到磁盘文件 logging.handlers.RotatingFileHandler # 循环日志文件
基本配置与使用(logging.basicConfig)
import logging logging.basicConfig(level=logging.INFO, format='%(message)s: %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s', datefmt='%Y-%m-%d %H:%M:%S', filename='log.log', filemode='a') logging.error(fullpath) # 日志将记录到 log.log 文件
#encoding: utf-8
#author: walker
#date: 2018-04-10 
#summary: 控制日志同时输出到控制台和日志文件,两种输出可以有不同的日志等级
import os
import logging.config
def GetMixLogger(logPathFile):
	logDir = os.path.dirname(logPathFile)
	if not os.path.isdir(logDir):
		os.mkdir(logDir)
	# log配置字典
	loggingDict = {
		'version': 1,
		'disable_existing_loggers': False,
		'formatters': {
			'fileFormatter': {
				'format': '%(message)s: %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s'
			},
			'consoleFormatter': {
				'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]: %(message)s'
			},
		},
		'filters': {},
		'handlers': {
			'consoleHandler': {
				'level': 'DEBUG',
				'class': 'logging.StreamHandler',  # 输出到 console
				'formatter': 'consoleFormatter'
			},
			'fileHandler': {
				'level': 'ERROR',
				'class': 'logging.FileHandler',  # 保存到文件
				'formatter': 'fileFormatter',
				'filename': logPathFile,  # 日志文件
				'encoding': 'utf-8', 
			},
		},
		'loggers': {
			'mix': {
				'handlers': ['consoleHandler', 'fileHandler'],  # 同时输出到控制台和日志文件
				'level': 'DEBUG',
				'propagate': True
			}
		},
	}
	
	logging.config.dictConfig(loggingDict)  # 导入配置
	logger = logging.getLogger('mix')  # 生成 logger 实例
	
	return logger
	
if __name__ == '__main__':
	mixLogger = GetMixLogger(r'F:\test\log.log')
	
	mixLogger.info('info message') 		# 同时输出到 console 和文件
	mixLogger.error('error message')	# 只输出到文件	用配置文件配置(logging.config.fileConfig)
*** walker ***
上一篇: python3安装解决ssl问题
下一篇: Mac同时安装python2和pytho
 51255
 50693
 41291
 38112
 32573
 29476
 28338
 23199
 23166
 21495
 1568°
 2287°
 1896°
 1833°
 2148°
 1879°
 2568°
 4303°
 4157°
 2963°