logging模块详解

在软件开发中,许多应用程序都需要日志文件记录,方便程序开发者在开发和维护的时候调用。

python中的日志模块logging可以帮助程序开发者日志记录的问题。在日志中可以记录的日志的级别有debug、info、warning、error、critical,根据程序开发者的需求自行设定日志级别

下面就以一个简单的日志记录到文件的例子看看logging模块的功能;

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import  logging
logging.basicConfig(filename='mylog.log',
                    level=logging.INFO,
                    format='%(asctime)s--%(name)s--%(levelname)s--%(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p')

while True:
    option = raw_input('please  input number:')
    if option.isdigit():
        logging.info('you input  number is correct')
    else:
        logging.error('Must be number,you input type is wrong')

在上面的示例中输入数字或非数字的时候,记录到文件mylog.log的内容是不同的:

输入如下:
please  input number:afdf
please  input number:123

在文件mylog.log中的日志记录如下:
2017-07-15 18:59:10 PM--root--ERROR--Must be number,you input type is wrong
2017-07-15 18:59:12 PM--root--INFO--you input  number is correct

对于上面的日志格式,详解如下:

%(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 用户输出的消息

 

 

 

 

 

 

 

 

 

 

 

 

 

 

如果想同时把log打印在屏幕和文件日志里,这个要比只向文件中写入日志麻烦点,首先要了解logging模块记录日志涉及的主要四个类,分别如下:

logger提供了应用程序可以直接使用的接口;

handler将(logger创建的)日志记录发送到合适的目的输出;

filter提供了细度设备来决定输出哪条日志记录;

formatter决定日志记录的最终输出格式。

下面就来实现同时把日志打印在屏幕上和文件日志里:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
logger = logging.getLogger('goser')
logger.setLevel(logging.DEBUG)

file_log = logging.FileHandler('log.log')
file_log.setLevel(logging.INFO)

ch_log = logging.StreamHandler()
ch_log.setLevel(logging.WARNING)

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

file_log.setFormatter(fomatter)
ch_log.setFormatter(fomatter)

logger.addHandler(file_log)
logger.addHandler(ch_log)

logger.debug('debug msg.....')
logger.info('info msg.....')
logger.warning('warning msg.....')
logger.error('error msg.....')
logger.critical('critical msg.....')

打印到屏幕上的日志为:

2017-07-15 20:06:07,898--goser--WARNING--warning msg.....
2017-07-15 20:06:07,898--goser--ERROR--error msg.....
2017-07-15 20:06:07,898--goser--CRITICAL--critical msg.....

记录到日志文件log.log中的记录为:

2017-07-15 20:06:07,898--goser--INFO--info msg.....
2017-07-15 20:06:07,898--goser--WARNING--warning msg.....
2017-07-15 20:06:07,898--goser--ERROR--error msg.....
2017-07-15 20:06:07,898--goser--CRITICAL--critical msg.....

 

posted @ 2017-07-15 20:07  goser  阅读(175)  评论(0)    收藏  举报