Python 官方文档:入门教程 => 点击学习
官方文档:Logging HOWTO官方文档:logging.config 模块日志的等级(level)如下,只有大于等于配置的等级时,日志才会被记录。# 默认等级为 WARNING NOTSET < DEBUG < INFO
官方文档: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 文件
python3之logging高级用法
用字典配置(logging.config.dictConfig)
#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 ***
--结束END--
本文标题: Python3 logging tips
本文链接: https://www.lsjlt.com/news/192988.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0