从零开始的Python学习Episode 14——日志操作

日志操作

一、logging模块

%(message)s 日志信息

%(levelno)s 日志级别

datefmt 设置时间格式

filename 设置日志保存的路径

level 设置日志记录的级别

filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”,“a”表示在原有的日志之后增添日志,“w”表示清除原有的日志后再添加新的日志。

配置日志级别、日志格式、输出位置

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='example.log',
                    filemode='w')

logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

在文件example.log中查看输出:

Wed, 24 Oct 2018 19:04:25 test2.py[line:9] DEBUG debug message
Wed, 24 Oct 2018 19:04:25 test2.py[line:10] INFO info message
Wed, 24 Oct 2018 19:04:25 test2.py[line:11] WARNING warning message
Wed, 24 Oct 2018 19:04:25 test2.py[line:12] ERROR error message
Wed, 24 Oct 2018 19:04:25 test2.py[line:13] CRITICAL critical message

%(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是一个树形层级结构,输出信息之前都要获得一个Logger(如果没有显示的获取则自动创建

并使用root Logger,如第一个例子所示)。

logger = logging.getLogger()返回一个默认的Logger也即root Logger,并应用默认的日志级别、

Handler和Formatter设置。

当然也可以通过Logger.setLevel(lel)指定最低的日志级别,可用的日志级别有logging.DEBUG、

logging.INFO、logging.WARNING、logging.ERROR、logging.CRITICAL。

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

fh = logging.FileHandler('example.log',mode = 'w')
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(ch)

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')

这里的文件模式在FileHandler里面设置。

猜你喜欢

转载自www.cnblogs.com/smilepup-hhr/p/9845669.html