logging模块的配置讲解
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(pathname)s-%(lineno)d %(message)s')
asctime : %(asctime)s 易读的时间格式: 默认情况下是'2003-07-08 16:49:45,896'的形式(逗号之后的数字是毫秒部分的时间)
filename: %(filename)s 路径名的文件名部分。
funcName :%(funcName)s 日志调用所在的函数名
levelname %(levelname)s 消息的级别名称('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
levelno %(levelno)s 对应数字格式的日志级别 (DEBUG, INFO, WARNING, ERROR,CRITICAL).
lineno %(lineno)d 发出日志记录调用的源码行号 (如果可用)。
module %(module)s 所在的模块名(如test6.py模块则记录test6)
message %(message)s 记录的信息
name %(name)s 调用的logger记录器的名称
process %(process)d 进程ID
processName %(processName)s 进程名
thread %(thread)d 线程ID
threadName %(threadName)s 线程名
logging模块的通用配置
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(pathname)s-%(lineno)d %(message)s') # 配置语句
logger_root = logging.getLogger('') # 拿到一个logging对象,使用该对象打印日志,比如 logger_root.info("this is info data")
getLogger('') 里面相同参数的为同一个对象.
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', # Mon, 16 Jul 2018 16:29:20 test.py[line:36] INFO
filename='log/log.txt', # 日志打印到的文件
filemode='w+'
)
方式二:可以指定编码,建议使用这种方式,不容易出现编码问题,或者使用通用配置,然后nohup打印到nohup.out 也可以
filehandler = logging.FileHandler(filename='./log/log.txt',encoding="utf-8")
fmter = logging.Formatter(fmt="%(asctime)s [%(levelname)s] %(pathname)s-%(lineno)d %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
filehandler.setFormatter(fmter)
logger_root = logging.getLogger('')
logger_root.addHandler(filehandler)
logger_root.setLevel(level=logging.DEBUG)
网友评论