实例一:日志写进一个文件
代码:
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s', #定义日志格式
datefmt='%Y-%m-%d %H:%M:%S %p', #定义asctime
filename='test.log', #定义日志文件
filemode='a') #定义写入模式,'a'是追加的意思
login():
while True:
try:
name = input('Input user name:')
password = int(input('Input password:')) #这里故意转成整型,触发异常
if name == 'andy' and password == 'nopasswd':
print('logging succeed!')
except ValueError as e:
logging.info(e) #这里写入日志
break
if __name__ == '__main__':
login()
format解释:
- asctime:时间,按照datefmt定义的显示,2018-01-10 14:50:25
- filename:报错的python文件名称
- line:%(lineno)d:报错的行数
- levelname:报错级别
- message:报错的信息
测试:
[root@admin_bak shell]# python3.6 test_log.py
Input user name:asdasd
Input password:asdsad #这是输入字符串,触发异常
查看日志
2018-01-10 11:54:40 AM test_log.py test_log.py[line:21] DEBUG invalid literal for int() with base 10: 'asdsad'
实例二:实现每天一个日志文件
代码:
import time
import logging
import logging.handlers
LOG_FILE = "ping.log" #设置日志文件名称
logger = logging.getLogger() #实例化logging
logger.setLevel(logging.INFO) #设置日志级别
#添加TimedRotatingFileHandler
#定义一秒换一次log文件的handlers
#保留3个旧log文件
fh = logging.handlers.TimedRotatingFileHandler(LOG_FILE, when='D', interval=1, backupCount=10)
#定义asctime
datefmt = '%Y-%m-%d %H:%M:%S'
#定义日志格式
format_str = '%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s'
formatter = logging.Formatter(format_str, datefmt)
fh.setFormatter(formatter)
logger.addHandler(fh)
while True:
time.sleep(0.1)
logging.info("test")
TimedRotatingFileHandler
TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]])#需要传的参数
filename:日志文件
when:
"S":second
"M":minutes
"H":Hours
"D":Days
"W":week day (0=monday)
interval:是指等待多少个"when"时间后,logging会自动新建文件,比如when='S',interval=10,就是10个一秒后新建文件,也就是10秒,when='D',interval=1,就是一天一个文件
backupCount:保留日志文件的个数