Python学习 :常用模块(三)----- 日志记录

常用模块(三)

七、logging模块

日志中包含的信息应有正常的程序访问日志,还可能有错误、警告等信息输出

python的 logging 模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging 的日志可以分为 debug() , info() , warning() , error() , critical() 5个级别

Eg.简单的日志记录

import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
>>> WARNING:root:warning message
    ERROR:root:error message
    CRITICAL:root:critical message
# 默认情况下logging模块将日志打印到了标准输出中(即屏幕上),且只显示了大于等于WARNING级别的日志
# 默认的日志级别设置为WARNING(日志级别等级 CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET)
# 默认的日志格式为日志级别:Logger名称:用户输出消息。

Eg.配置日志的级别,日志格式,输出位置

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='test.log',  # 在当前目录下创建日志记录文件
                    filemode='w')  # 文件的打开方式为 w
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

format参数中可以用到的格式化串:

%(name)s       # Logger的名字
%(levelno)s    # 数字形式的日志级别
%(levelname)s  # 文本形式的日志级别
%(pathname)s   # 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s   # 调用日志输出函数的模块的文件名
%(module)s     # 调用日志输出函数的模块名
%(funcName)s   # 调用日志输出函数的函数名
%(lineno)d     # 调用日志输出函数的语句所在的代码行
%(created)f    # 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d # 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s    # 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d     # 线程ID。可能没有
%(threadName)s # 线程名。可能没有
%(process)d    # 进程ID。可能没有
%(message)s    # 用户输出的消息

logger 对象 :使用 logger 对象,让文件以及屏幕同时输出日志

import logging
logger = logging.getLogger()

# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log')  # 文件输出流对象
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()  # 标准输出流对象(即屏幕输出)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh.setFormatter(formatter)  # 取得要输出的标准格式
ch.setFormatter(formatter)  # 取得要输出的标准格式

logger.addHandler(fh)  # logger对象可以添加多个fh和ch对象
logger.addHandler(ch)

logger.setLevel(logging.DEBUG) # 设置日志的级别

# 最后设置日志想要记录的不同信息
logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')

 

原文地址:https://www.cnblogs.com/ArticleYeung/p/9860279.html