log日志简介以及使用 日志介绍日志概念用于记录系统运行时的信息是对一个事件的记录日志作用调试程序可以用来判断程序是否运行正常可以用来分析和定位问题可以用来做用户行为分析和数据统计日志级别调试级别DEBUG记录一些代码的调试信息信息级别INFO记录一些正常的操作信息警告级别Warring记录一些警告日志信息但不会影响系统的功能及正常运行某些功能使用时提示警告了错误级别Error记录系统运行时的错误信息说明系统的某些功能不能正常运行某个功能不能使用error严重错误级别critical记录系统运行时的严重错误信息有可能导致整个系统都不能运行。系统崩溃就是critical日志模块logging日志模块的使用导入日志模块Python自带import logging使用日志模块的方法日志输出logging.info(msg)日志级别设置logging.basicConfig(levellogging.DEBUG)日志格式设置logging.basicConfig(levellogging.DEBUG,formatfmt)格式样式设置fmt %(asctime)s %(levelname)s [%(name)s] - %(message)s日志输出到文件设置logging.basicConfig(filenamelog/log01.log,levellogging.DEBUG,formatfmt)importlogging# 定义一个格式化的字符串# 时间:%(asctime)s 文本形式日志级别: %(levelname)s# 调用日志输出函数模块的完整路径名%(filename)s语句所在代码行%(lineno)d#用户输出的信息%(message)sfmt%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s#设置日志级别、日志格式、日志输出到文件logging.basicConfig(levellogging.DEBUG,formatfmt.filenamelog/log01.log)# 调用logging模块输出日志。会根据级别输出不同日志默认warninglogging.debug(这是调试级别日志)logging.info(这是信息级别的日志)logging.warning(这是警告级别日志)logging.error(这是错误级别的日志)logging.critical(这是严重错误级别日志)日志组件日志器 logger 是程序的入口主要用来记录日志的信息处理器 handler 决定了日志的输出目的地格式器 formatter 决定了日志的输出格式示例importloggingimportlogging.handlers#1.创建日志器,设置级别loggerlogging.getLogger()logger.setLevel(logging.DEBUG)#2.1创建处理器设置级别,输出到控制台handler_consolelogging.StreamHandler()handler_console.setLevel(logging.DEBUG)#2.2创建处理器设置级别,输出到文件handler_filelogging.handlers.TimedRotatingFileHandler(log/tlog.log,whenM,interval1,backupCount3)handler_file.setLevel(logging.DEBUG)#3设置格式fmt%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s#3创建格式器formatterlogging.Formatter(fmtfmt)#4将格式器添分别加到两个处理器(文件和控制台)handler_file.setFormatter(formatter)handler_console.setFormatter(formatter)#5将处理器添加到日志器两个处理器logger.addHandler(handler_console)logger.addHandler(handler_file)#6日志输出logger.debug(~~这是debug message~~~)