ITPub博客

首页 > IT职业 > IT图书 > Python3 logging tips

Python3 logging tips

IT图书 作者:kalt 时间:2021-09-09 09:36:47 0 删除 编辑

  • 官方文档:Logging HOWTO

  • 官方文档:logging.config 模块

  • 日志的等级(level)如下,只有大于等于配置的等级时,日志才会被记录。

12 # 默认等级为 WARNINGNOTSET 
  • 官方模块有十几个 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:testlog.log')         mixLogger.info('info message')        # 同时输出到 console 和文件    mixLogger.error('error message')   # 只输出到文件  
  • 用配置文件配置(logging.config.fileConfig)


*** walker ***


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1805/viewspace-2810952/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    121
  • 访问量
    893