Python logging 日志模块

logging模块  

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别,下面我们看一下怎么用。

最简单用法

1
2
3
4
5
6
7
8
import logging
 
logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")
 
#输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down

看一下这几个日志级别分别代表什么意思

LevelWhen it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

  

如果想把日志写到文件里,也很简单

1
2
3
4
5
6
import logging
 
logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。

1
logging.basicConfig(filename='example.log',level=logging.INFO)

感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!

1
2
3
4
5
6
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logging.warning('is when this event was logged.')
 
#输出
2010-12-12 11:46:36 is when this event was logged.

  

如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

  • Loggers expose the interface that application code directly uses.
  • Handlers send the log records (created by loggers) to the appropriate destination.
  • Filters provide a finer grained facility for determining which log records to output.
  • Formatters specify the layout of log records in the final output.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import logging
 
# 创建一个 logging 对象, TEST-LOG 为定义这个LOG的 name  [ %(name)s ]
logger = logging.getLogger('TEST-LOG')
# 设置日志 级别为 DEBUG, 全局日志 级别 全局级别 优先级高
logger.setLevel(logging.DEBUG)
 
 
# 创建一个 用于 屏幕输出 的 StreamHandeler
ch = logging.StreamHandler()
# 设置日志 级别为 DEBUG
ch.setLevel(logging.DEBUG)
 
 
# 创建一个 用于 文件输出 的 FileHandler, 并输出到 access.log 文件
fh = logging.FileHandler("access.log")
# 设置日志 级别为 WARNING
fh.setLevel(logging.WARNING)
 
 
# 创建一个 日志格式 Formatter (
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
 
# 让 屏幕输出,与 文件输出 都按照 formatter 这个格式生成
ch.setFormatter(formatter)
fh.setFormatter(formatter)
 
 
# 讲 StreamHandeler 与 FileHandler 添加到 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('critical message')

  

 日志 格式 里的函数:

 filemode: 和file函数意义相同,指定日志文件的打开模式,'w''a'

 format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:

 %(levelno)s: 打印日志级别的数值

 %(levelname)s: 打印日志级别名称

 %(filename)s: 打印当前执行程序名

 %(pathname)s: 打印当前执行程序的路径,就是sys.argv[0]

 %(funcName)s: 打印日志的当前函数

 %(lineno)d: 打印日志的当前行号

 %(asctime)s: 打印日志的时间

 %(thread)d: 打印线程ID
 %(threadName)s: 打印线程名称

 %(process)d: 打印进程ID

 %(message)s: 打印日志信息

 datefmt: 指定时间格式,同time.strftime()

 level: 设置日志级别,默认为logging.WARNING

 stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

 


日志文件 轮转
 :

 import logging

 from logging.handlers import RotatingFileHandler

 #######################################################

 #定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M

 Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5)

 Rthandler.setLevel(logging.INFO)

 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

 Rthandler.setFormatter(formatter)

 logging.getLogger('').addHandler(Rthandler)

 ########################################################

 


logging 的几种handle方式如下:

logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件

logging.FileHandler: 日志输出到文件

日志回滚方式,实际使用时用RotatingFileHandler和TimedRotatingFileHandler

logging.handlers.BaseRotatingHandler

logging.handlers.RotatingFileHandler

logging.handlers.TimedRotatingFileHandler

logging.handlers.SocketHandler: 远程输出日志到TCP/IP sockets

logging.handlers.DatagramHandler:  远程输出日志到UDP sockets

logging.handlers.SMTPHandler:  远程输出日志到邮件地址

logging.handlers.SysLogHandler: 日志输出到syslog

logging.handlers.NTEventLogHandler: 远程输出日志到Windows NT/2000/XP的事件日志

logging.handlers.MemoryHandler: 日志输出到内存中的制定buffer

logging.handlers.HTTPHandler: 通过"GET""POST"远程输出到HTTP服务器

 


 

posted @ 2016-07-12 12:16  丶小炒肉  阅读(237)  评论(0)    收藏  举报