Python模块:日志输出—logging模块
1. 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方法添加0到多個handler,每個handler又可以定義不同日志級別,以實現日志分級過濾顯示。
? ? ? ? filter:提供一種優雅的方式決定一個日志記錄是否發送到handler。
? ? ? ? formatter:指定日志記錄輸出的具體格式。formatter的構造方法需要兩個參數:消息的格式字符串和日期字符串,這兩個參數都是可選的。
? ? ? ? 與log4j類似,logger,handler和日志消息的調用可以有具體的日志級別(Level),只有在日志消息的級別大于logger和handler的級別。
?
import logging import logging.handlers LOG_FILE = 'tst.log' handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024, backupCounts = 5) # 實例化handler fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s' formatter = logging.Formatter(fmt) # 實例化formatter handler.setFormatter(formatter) # 為handler添加formatter logger = logging.getLogger('tst') # 獲取名為tst的logger logger.addHandler(handler) # 為logger添加handler logger.setLevel(logging.DEBUG) logger.info('first info message') logger.debug('first debug message')? ? ? ? 輸出:
2012-03-04 23:21:59,682 - log_test.py:16 - tst - first info message 2012-03-04 23:21:59,682 - log_test.py:17 - tst - first debug message? ? ? ? 關于formatter的配置,采用的是%(<dict key>)s的形式,就是字典的關鍵字替換。提供的關鍵字包括:
?
| %(name)s | Name of the logger (logging channel). |
| %(levelno)s | Numeric logging level for the message (DEBUG,?INFO,?WARNING,?ERROR,?CRITICAL). |
| %(levelname)s | Text logging level for the message ('DEBUG',?'INFO',?'WARNING',?'ERROR',?'CRITICAL'). |
| %(pathname)s | Full pathname of the source file where the logging call was issued (if available). |
| %(filename)s | Filename portion of pathname. |
| %(module)s | Module (name portion of filename). |
| %(funcName)s | Name of function containing the logging call. |
| %(lineno)d | Source line number where the logging call was issued (if available). |
| %(created)f | Time when the?LogRecord?was created (as returned by?time.time()). |
| %(relativeCreated)d | Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded. |
| %(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). |
| %(msecs)d | Millisecond portion of the time when the?LogRecord?was created. |
| %(thread)d | Thread ID (if available). |
| %(threadName)s | Thread name (if available). |
| %(process)d | Process ID (if available). |
| %(message)s | The logged message, computed as?msg?%?args. |
? ? ? ? 這個是摘自官網,提供了很多信息。
2. logging的配置
? ? ? ? logging的配置可以采用python代碼或是配置文件。python代碼的方式就是在應用的主模塊中,構建handler,handler,formatter等對象。而配置文件的方式是將這些對象的依賴關系分離出來放在文件中。比如前面的例子就類似于python代碼的配置方式。這里看一下采用配置文件的方式。
?
[python] view plaincopyprint?? ? ? ? loggin.conf采用了模式匹配的方式進行配置,正則表達式是r'^[(.*)]$',從而匹配出所有的組件。對于同一個組件具有多個實例的情況使用逗號‘,’進行分隔。對于一個實例的配置采用componentName_instanceName配置塊。使用這種方式還是蠻簡單的。
?
[plain] view plaincopyprint?? ? ? ? 在指定handler的配置時,class是具體的handler類的類名,可以是相對logging模塊或是全路徑類名,比如需要RotatingFileHandler,則class的值可以為:RotatingFileHandler或者logging.handlers.RotatingFileHandler。args就是要傳給這個類的構造方法的參數,就是一個元組,按照構造方法聲明的參數的順序。
? ? ? ? 輸出:
?
[plain] view plaincopyprint?? ? ? ? 這里還要明確一點,logger對象是有繼承關系的,比如名為a.b和a.c的logger都是名為a的子logger,并且所有的logger對象都繼承于root。如果子對象沒有添加handler等一些配置,會從父對象那繼承。這樣就可以通過這種繼承關系來復用配置。
3. 多模塊使用logging
logging模塊保證在同一個python解釋器內,多次調用logging.getLogger('log_name')都會返回同一個logger實例,即使是在多個模塊的情況下。所以典型的多模塊場景下使用logging的方式是在main模塊中配置logging,這個配置會作用于多個的子模塊,然后在其他模塊中直接通過getLogger獲取Logger對象即可。? ? ? ? 這里使用上面配置文件:
?
[plain] view plaincopyprint??
? ? ? ? 主模塊main.py:
?
[python] view plaincopyprint?? ? ? ? 子模塊mod.py:
?
[python] view plaincopyprint?? ? ? ? 子子模塊submod.py:
?
[python] view plaincopyprint?? ? ? ? 然后運行python main.py,控制臺輸出:
?
?
[plain] view plaincopyprint?? ? ? ? 可以看出,和預想的一樣,然后在看一下tst.log,logger配置中的輸出的目的地:
?
?
[plain] view plaincopyprint?? ? ? ? tst.log中沒有root logger輸出的信息,因為logging.conf中配置了只有main logger及其子logger使用RotatingFileHandler,而root logger是輸出到標準輸出。
?
轉:http://blog.csdn.net/chosen0ne/article/details/7319306
總結
以上是生活随笔為你收集整理的Python模块:日志输出—logging模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 亚马逊高管解读 Q4 财报:首要任务是降
- 下一篇: 谷歌母公司Alphabet发布财报 净利