1. 程式人生 > >Python logging模塊

Python logging模塊

ued .exe created 文件的 一點 lex 字符 dha lis

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 nameFormatDescription
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

本文內容轉自:http://www.cnblogs.com/Richardzhu/p/5303887.html

Python logging模塊