官方文档:Logging HOWTO
官方文档:logging.config 模块
日志的等级(level)如下,只有大于等于配置的等级时,日志才会被记录。
| 12 | # 默认等级为 WARNINGNOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL |
官方模块有十几个 Handler(Useful Handlers),存在于 logging 和 logging.handlers 模块。常用的有:
| 123 | logging.StreamHandler # 输出日志到控制台时使用(sys.stderr)logging.FileHandler # 输出日志到磁盘文件logging.handlers.RotatingFileHandler # 循环日志文件 |
基本配置与使用(logging.basicConfig)
import logginglogging.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 osimport 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 ***
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦