logging.basicConfig
简单配置import logging
#同时输出文件和控制台
fh = logging.FileHandler(‘tmp.log‘,encoding=‘utf-8‘)
sh = logging.StreamHandler()
logging.basicConfig(
# 日志格式
# 时间、代码所在文件名、代码行号、日志级别名字、日志信息
format = ‘%(asctime)s - %(name)s - %(levelname)s[line:%(lineno)d] - %(module)s : %(message)s‘,
# 打印日志的时间
datefmt = ‘%Y-%m-%d %H:%M:%S %p‘,
#设置日志输出路径
# filename=‘tmp.log‘,
#设置级别
level=logging.DEBUG,
handlers =[fh,sh]
)
logging.basicConfig函数中,可以指定日志的输出格式format,这个参数可以输出很多有用的信息,如上例所示:
》》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被忽略
》》logging打印信息函数:
logging.debug(‘This is debug message‘)
logging.info(‘This is info message‘)
logging.warning(‘This is warning message‘)
我在工作中给的常用格式在前面已经看到了。就是:
format=‘%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s‘
这个格式可以输出日志的打印时间,是哪个模块输出的,输出的日志级别是什么,以及输入的日志内容。
按时间切割日志
from logging import handlers
import time
rh_size = handlers.RotatingFileHandler(‘myapp.log‘,maxBytes=1024,backupCount=5) # 按照文件大小切割 满1024字节切割 切割5次 超出覆盖
fh_size = handlers.TimedRotatingFileHandler(filename=‘x2.log‘,when=‘s‘,interval=10,encoding=‘utf-8‘) #按照时间切割 每5s切割
logging.basicConfig(
# 日志格式
# 时间、代码所在文件名、代码行号、日志级别名字、日志信息
format = ‘%(asctime)s - %(name)s - %(levelname)s[line:%(lineno)d] - %(module)s : %(message)s‘,
# 打印日志的时间
datefmt = ‘%Y-%m-%d %H:%M:%S %p‘,
#设置日志输出路径
# filename=‘tmp.log‘,
#设置级别
level=logging.DEBUG,
handlers=[fh_size,rh_size]
)
for i in range(1,1000):
time.sleep(1)
logging.error(‘这是第%s输出了‘%(i))
原文:https://www.cnblogs.com/Ajin0427/p/13252013.html