
一 日志级别
CRITICAL = 50 #FATAL = CRITICALERROR = 40WARNING = 30 #WARN = WARNINGINFO = 20DEBUG = 10NOTSET = 0 #不设置
二 默认级别为warning,默认打印到终端
import logginglogging.debug('调试debug')logging.info('消息info')logging.warning('警告warn')logging.error('错误error')logging.critical('严重critical')'''WARNING:root:警告warnERROR:root:错误errorCRITICAL:root:严重critical'''
三 为logging模块指定全局配置,针对所有logger有效,控制打印到文件中
# 可在logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有# filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。# filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。# format:指定handler使用的日志显示格式。# datefmt:指定日期时间格式。# level:设置rootlogger(后边会讲解具体概念)的日志级别# stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
logging.basicConfig()
import logginglogging.basicConfig(filename='access.log',format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',datefmt='%Y-%m-%d %H:%M:%S %p',level=10)logging.debug('调试debug')logging.info('消息info')logging.warning('警告warn')logging.error('错误error')logging.critical('严重critical')
format参数中可能用到的格式化串:
%(name)s:Logger的名字,并非用户名,详细查看%(levelno)s:数字形式的日志级别%(levelname)s:文本形式的日志级别%(pathname)s:调用日志输出函数的模块的完整路径名,可能没有%(filename)s:调用日志输出函数的模块的文件名%(module)s:调用日志输出函数的模块名%(funcName)s:调用日志输出函数的函数名%(lineno)d:调用日志输出函数的语句所在的代码行%(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示%(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数%(asctime)s:字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒%(thread)d:线程ID。可能没有%(threadName)s:线程名。可能没有%(process)d:进程ID。可能没有%(message)s:用户输出的消息
%(name)s:Logger的名字,并非用户名,详细查看
import logginglogging.basicConfig(format='%(name)s',level=10)logging.debug('调试debug')# root
%(levelno)s:数字形式的日志级别
import logginglogging.basicConfig(format='%(levelno)s',level=10)logging.debug('调试debug')# 10
%(levelname)s:文本形式的日志级别
import logginglogging.basicConfig(format='%(levelname)s',level=10)logging.debug('调试debug')# DEBUG
%(pathname)s:调用日志输出函数的模块的完整路径名,可能没有
import logginglogging.basicConfig(format='%(pathname)s',level=10)logging.debug('调试debug')# F:/学习课件/python/pycharm/测试.py
%(filename)s:调用日志输出函数的模块的文件名
import logginglogging.basicConfig(format='%(filename)s',level=10)logging.debug('调试debug')# 测试.py
%(module)s:调用日志输出函数的模块名
import logginglogging.basicConfig(format='%(module)s',level=10)logging.debug('调试debug')# 测试
%(funcName)s:调用日志输出函数的函数名
import logginglogging.basicConfig(format='%(funcName)s',level=10)logging.debug('调试debug')# <module>
%(lineno)d:调用日志输出函数的语句所在的代码行
import logginglogging.basicConfig(format='%(lineno)d',level=10)logging.debug('调试debug')# 7
%(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示`
import logginglogging.basicConfig(format='%(created)f',level=10)logging.debug('调试debug')# 1607770646.867305
%(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数
import loggingimport timelogging.basicConfig(format='%(relativeCreated)d',level=10)time.sleep(2)logging.debug('调试debug') # 2002time.sleep(2)logging.debug('调试debug') # 4003
%(asctime)s:字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
import logginglogging.basicConfig(format='%(asctime)s',level=10)logging.debug('调试debug')# 2020-12-12 19:01:19,503
%(thread)d:线程ID。可能没有
import logginglogging.basicConfig(format='%(thread)d',level=10)logging.debug('调试debug')# 12592
%(threadName)s:线程名。可能没有
import logginglogging.basicConfig(format='%(threadName)s',level=10)logging.debug('调试debug')# MainThread
%(process)d:进程ID。可能没有
import logginglogging.basicConfig(format='%(process)d',level=10)logging.debug('调试debug')# 2984
%(message)s:用户输出的消息
import logginglogging.basicConfig(format='%(message)s',level=10)logging.debug('调试debug')# 调试debug
四 logging模块的Formatter,Handler,Logger,Filter对象
# logger:产生日志的对象# Filter:过滤日志的对象# Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,StreamHandler用来打印到终端# Formatter对象:可以定制不同的日志格式对象,然后绑定给不同的Handler对象使用,以此来控制不同的Handler的日志格式
'''critical=50error =40warning =30info = 20debug =10'''import logging#1、logger对象:负责产生日志,然后交给Filter过滤,然后交给不同的Handler输出logger=logging.getLogger(__file__)#2、Filter对象:不常用,略#3、Handler对象:接收logger传来的日志,然后控制输出h1=logging.FileHandler('t1.log') #打印到文件h2=logging.FileHandler('t2.log') #打印到文件h3=logging.StreamHandler() #打印到终端#4、Formatter对象:日志格式formmater1=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',datefmt='%Y-%m-%d %H:%M:%S %p',)formmater2=logging.Formatter('%(asctime)s : %(message)s',datefmt='%Y-%m-%d %H:%M:%S %p',)formmater3=logging.Formatter('%(name)s %(message)s',)#5、为Handler对象绑定格式h1.setFormatter(formmater1)h2.setFormatter(formmater2)h3.setFormatter(formmater3)#6、将Handler添加给logger并设置日志级别logger.addHandler(h1)logger.addHandler(h2)logger.addHandler(h3)logger.setLevel(10)#7、测试logger.debug('debug')logger.info('info')logger.warning('warning')logger.error('error')logger.critical('critical')
五 配置文件
程序文件
"""settings.pylogging配置"""import osimport logging.config# 定义三种日志输出格式 开始standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d][%(levelname)s][%(message)s]' #其中name为getlogger指定的名字simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'# 定义日志输出格式 结束logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录logfile_name = 'all2.log' # log文件名# 如果不存在定义的日志目录就创建一个if not os.path.isdir(logfile_dir):os.mkdir(logfile_dir)# log文件的全路径logfile_path = os.path.join(logfile_dir, logfile_name)# log配置字典LOGGING_DIC = {'version': 1,'disable_existing_loggers': False,'formatters': {'standard': {'format': standard_format},'simple': {'format': simple_format},},'filters': {},'handlers': {#打印到终端的日志'console': {'level': 'DEBUG','class': 'logging.StreamHandler', # 打印到屏幕'formatter': 'simple'},#打印到文件的日志,收集info及以上的日志'default': {'level': 'DEBUG','class': 'logging.handlers.RotatingFileHandler', # 保存到文件'formatter': 'standard','filename': logfile_path, # 日志文件'maxBytes': 1024*1024*5, # 日志大小 5M'backupCount': 5,'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了},},'loggers': {#logging.getLogger(__name__)拿到的logger配置'': {'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕'level': 'DEBUG','propagate': True, # 向上(更高level的logger)传递},},}def load_my_logging_cfg():logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置logger = logging.getLogger(__name__) # 生成一个log实例logger.info('It works!') # 记录该文件的运行状态if __name__ == '__main__':load_my_logging_cfg()
调用程序
'''common.py'''import settings# !!!强调!!!# 1、logging是一个包,需要使用其下的config、getLogger,可以如下导入# from logging import config# from logging import getLogger# 2、也可以使用如下导入import logging.config # 这样连同logging.getLogger都一起导入了,然后使用前缀logging.config.# 3、加载配置logging.config.dictConfig(settings.LOGGING_DIC)# 4、输出日志logger1=logging.getLogger('用户交易')logger1.info('xiaowo转入666')# logger2=logging.getLogger('专门的采集') # 名字传入的必须是'专门的采集',与LOGGING_DIC中的配置唯一对应# logger2.debug('专门采集的日志')
logging 配置文件格式
# 日志级别与配置import logging# 一:日志配置logging.basicConfig(# 1、日志输出位置:1、终端 2、文件# filename='access.log', # 不指定,默认打印到终端# 2、日志格式format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',# 3、时间格式datefmt='%Y-%m-%d %H:%M:%S %p',# 4、日志级别# critical => 50# error => 40# warning => 30# info => 20# debug => 10level=30,)# 二:输出日志logging.debug('调试debug')logging.info('消息info')logging.warning('警告warn')logging.error('错误error')logging.critical('严重critical')
