Python logging 模块

将日志打印到屏幕上

import logging

logging.debug('This is an debug information')
logging.info('This is an info level information')
logging.warning('This is an warnning level information')

 默认情况下,logging模块会把日志打印到屏幕上,并且默认的日志级别为: WARNING.

 所以输出结果为:

WARNING:root:This is an warnning level information

 日志的级别为: Critical > Error > Warning > Info > Debug

通过logging.basicConfig 函数对日志的输出格式及方式做配置

import logging

logging.basicConfig(level=logging.DEBUG, filename='myapp.log', filemode='a', datefmt='%a, %d %b %Y %H:%M:%S',
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')

logging.debug('This is an debug information')
logging.info('This is an info level information')
logging.warning('This is an warnning level information')

 myapp.log 中的内容为:

Thu, 16 Nov 2017 10:39:16 logtest.py[line:6] DEBUG This is an debug information
Thu, 16 Nov 2017 10:39:16 logtest.py[line:7] INFO This is an info level information
Thu, 16 Nov 2017 10:39:16 logtest.py[line:8] WARNING This is an warnning level information

logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
 %(levelno)s: 打印日志级别的数值
 %(levelname)s: 打印日志级别名称
 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
 %(filename)s: 打印当前执行程序名
 %(funcName)s: 打印日志的当前函数
 %(lineno)d: 打印日志的当前行号
 %(asctime)s: 打印日志的时间
 %(thread)d: 打印线程ID
 %(threadName)s: 打印线程名称
 %(process)d: 打印进程ID
 %(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

将日志同时输出到文件和屏幕

import logging

logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='myapp.log',
                filemode='w')

#################################################################################################
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################

logging.debug('This is an debug information')
logging.info('This is an info level information')
logging.warning('This is an warnning level information')

 除了在myapp.log里面有之上的内容以外,屏幕上会显示:

root: INFO This is an info level information
root: WARNING This is an warnning level information

 logging之日志回滚

https://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html

原文地址:https://www.cnblogs.com/diaolanshan/p/7843032.html