一、引言
之前在写一些小程序的时候想把日志内容打到文件中,所以就自己写了一个logger.py的程序,如下:
#!/usr/bin/python
# -*- coding=utf-8 -*- import time
import os def record_log(names,act,things,price,money):
#日志文件名
logfile = 'log.txt'
#数据插入的日期
date = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
record_line = date + '\t' + names + '\t' + act + '\t' + things + '\t' + price + '\t' + str(money) + '\n'
#判断日志文件是否存在,如果不存在就创建一个新文件,并插入单位名称
if not os.path.exists(logfile):
f = open(logfile,'w')
record = '日期' + '\t\t' + '用户' + '\t\t' + '动作' + '\t\t' + '事务' + '\t\t' + '价格' + '\t\t' + '余额' + '\n'
f.write(record)
f.close()
f = open(logfile,'a')
f.write(record_line)
f.flush()
f.close()
后来发现有logging模块,感觉自己之前的写的好low!今天就来介绍一下logging模块。
二、logging模块
Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。
logging模块与log4j的机制是一样的,只是具体的实现细节不同。模块提供logger,handler,filter,formatter。
logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。
handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。
filter:提供一种优雅的方式决定一个日志记录是否发送到handler。
formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。
与log4j类似,logger,handler和日志消息的调用可以有具体的日志级别(level),只有在日志消息的级别大于logger和handler的级别。
#!/usr/bin/env python
# -*- coding=utf-8 -*- import logging #创建一个logging的实例logger
logger = logging.getLogger('Richard')
#设定全局日志级别为DEBUG
logger.setLevel(logging.INFO)
#创建一个屏幕的handler,并且设定级别为DEBUG
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#创建一个日志文件的handler,并且设定级别为DEBUG
fh = logging.FileHandler("access.log")
fh.setLevel(logging.CRITICAL)
#设置日志的格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
#add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)
#add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)
#'application' code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("crititcal message")
输出结果:
"D:\Program Files (x86)\python34\python.exe" F:/Python/Alex/s12/Blog/log.py
2016-03-22 06:13:09,764 - Richard - INFO - info message
2016-03-22 06:13:09,764 - Richard - WARNING - warn message
2016-03-22 06:13:09,764 - Richard - ERROR - error message
2016-03-22 06:13:09,764 - Richard - CRITICAL - crititcal message access.log:
2016-03-22 06:13:09,764 - Richard - CRITICAL - crititcal message
在这里需要说明的一点是logger.setLevel(logging.INFO)和ch.setLevel(logging.DEBUG)的区别:
通过例子来看:
#设定全局日志级别为CRITICAL
logger.setLevel(logging.CRITICAL)
#创建一个屏幕的handler,并且设定级别为DEBUG
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#创建一个日志文件的handler,并且设定级别为INFO
fh = logging.FileHandler("access.log")
fh.setLevel(logging.INFO) 输出结果:
"D:\Program Files (x86)\python34\python.exe" F:/Python/Alex/s12/Blog/log.py
2016-03-22 06:20:10,712 - Richard - CRITICAL - crititcal message access.log:
2016-03-22 06:20:10,712 - Richard - CRITICAL - crititcal message
就是全局日志级别为CRITICAL的话,局部变量想设置成INFO或者DEBUG都会失效。
由此可以得出全局的比局部的级别要高,加入全局的设成DEBUG的话,局部可以设成WARNING,那么logging只会输出WARNG、ERROR、CRITICAL这三种类型。
备注:关于formatter的配置,采用的是%(<dict key>)s的形式,就是字典的关键字替换。提供的关键字包括:
Attribute name | Format | Description |
---|---|---|
args | You shouldn’t need to format this yourself. | The tuple of arguments merged into msg to produce message , or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary). |
asctime | %(asctime)s |
Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time). |
created | %(created)f |
Time when the LogRecord was created (as returned by time.time() ). |
exc_info | You shouldn’t need to format this yourself. | Exception tuple (à la sys.exc_info ) or, if no exception has occurred, None. |
filename | %(filename)s |
Filename portion of pathname . |
funcName | %(funcName)s |
Name of function containing the logging call. |
levelname | %(levelname)s |
Text logging level for the message ('DEBUG' , 'INFO' , 'WARNING' , 'ERROR' ,'CRITICAL' ). |
levelno | %(levelno)s |
Numeric logging level for the message (DEBUG , INFO , WARNING , ERROR ,CRITICAL ). |
lineno | %(lineno)d |
Source line number where the logging call was issued (if available). |
module | %(module)s |
Module (name portion of filename ). |
msecs | %(msecs)d |
Millisecond portion of the time when the LogRecord was created. |
message | %(message)s |
The logged message, computed as msg % args . This is set whenFormatter.format() is invoked. |
msg | You shouldn’t need to format this yourself. | The format string passed in the original logging call. Merged with args to produce message , or an arbitrary object (see Using arbitrary objects as messages). |
name | %(name)s |
Name of the logger used to log the call. |
pathname | %(pathname)s |
Full pathname of the source file where the logging call was issued (if available). |
process | %(process)d |
Process ID (if available). |
processName | %(processName)s |
Process name (if available). |
relativeCreated | %(relativeCreated)d |
Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded. |
stack_info | You shouldn’t need to format this yourself. | Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record. |
thread | %(thread)d |
Thread ID (if available). |
threadName | %(threadName)s |
Thread name (if available). |
logging官网地址:
https://docs.python.org/3.5/library/logging.html