python 日志文件记录
# -*- coding:utf-8 -*- #
import logging
log_format = '%(filename)s [%(asctime)s] [%(levelname)s] %(message)s'
logging.basicConfig(format=log_format, datefmt='%Y-%m-%d %H:%M:%S %p', level=logging.DEBUG)
logging.debug('this message should be logged')
# %(levelname):日志级别的名字格式
# %(levelno)s:日志级别的数字表示
# %(name)s:日志名字
# %(funcName)s:函数名字
# %(asctime):日志时间,可以使用datefmt去定义时间格式,如上图。
# %(pathname):脚本的绝对路径
# %(filename):脚本的名字
# %(module):模块的名字
# %(thread):thread id
# %(threadName):线程的名字
# logging.basicConfig(format=log_format,datefmt='%Y-%m-%d %H:%M:%S %p',level=logging.DEBUG) #设置日志输出格式和级别。
log_filename = "logging_test.log"
logging.basicConfig(filename=log_filename, filemode='w', level=logging.DEBUG)
logging.debug('this message should be logged')
logging.info('So should this')
logging.warning('And this, too')
# 看了吧,日志的设置都是使用basicConfig()方法,需要注意的是,日志写入文件的默认方式是‘a’,也就是追加,如果想覆盖文件,则使用如上图那样,使用filemode='w'。