Python Logging模塊的簡單使用

来源:http://www.cnblogs.com/wswang/archive/2016/12/06/6138304.html
-Advertisement-
Play Games

前言 日誌是非常重要的,最近有接觸到這個,所以系統的看一下Python這個模塊的用法。本文即為Logging模塊的用法簡介,主要參考文章為Python官方文檔,鏈接見參考列表。 另外,Python的 "HOWTOs文檔" 很詳細,連日誌該怎麼用都寫了,所以有英文閱讀能力的同學建議去閱讀一下。 Log ...


前言

日誌是非常重要的,最近有接觸到這個,所以系統的看一下Python這個模塊的用法。本文即為Logging模塊的用法簡介,主要參考文章為Python官方文檔,鏈接見參考列表。

另外,Python的HOWTOs文檔很詳細,連日誌該怎麼用都寫了,所以有英文閱讀能力的同學建議去閱讀一下。

Logging模塊構成

組成

主要分為四個部分:

  • Loggers:提供應用程式直接使用的介面
  • Handlers:將Loggers產生的日誌傳到指定位置
  • Filters:對輸出日誌進行過濾
  • Formatters:控制輸出格式

日誌級別

Level Numeric value When it’s used
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.
INFO 20 Confirmation that things are working as expected.
WARNING 30 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 40 Due to a more serious problem, the software has not been able to perform some function.
CRITICAL 50 A serious error, indicating that the program itself may be unable to continue running.
NOSET 0 getattr(logging, loglevel.upper())

預設級別是WARNING,可以使用列印到屏幕上的方式記錄,也可以記錄到文件中。

模塊使用示例

簡單例子

列印輸出
In [5]: import logging

In [6]: logging.warning("FBI warning")
WARNING:root:FBI warning

In [7]: logging.info("information")
# 沒有列印是因為預設級別是warning
輸出到文件中
In [4]: import logging

In [5]: logging.basicConfig(filename='example.log', level=logging.DEBUG)

In [6]: logging.debug("debug")

In [7]: logging.warning('warning')

In [8]: logging.info('info')

In [9]: ls
C++ STL/     a.py         example.log  parser/      test.sh*

In [10]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info

In [14]: logging.warning('new warning')
# 註意這種是直接往後面添加,也就是add的,若是想覆蓋內容可以更改文件寫入方式

In [15]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info
WARNING:root:new warning

# 覆蓋的方式寫入例子
(test) ➜  test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import logging

In [2]: logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

In [3]: logging.warning('FBI warning')

In [4]: ls
C++ STL/     a.py         example.log  parser/      test.sh*

In [5]: cat example.log
WARNING:root:FBI warning

In [6]: quit
(test) ➜  test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import logging

In [2]: logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

In [3]: logging.warning('warning')

In [4]: cat example.log
WARNING:root:warning
變數的使用

print語句中使用變數一樣,如:

In [5]: logging.warning('%s before you %s', 'Look', 'leap!')

In [6]: cat example.log
WARNING:root:warning
WARNING:root:Look before you leap!
輸出格式

可以在basicConfig中設置,參數名稱可以參見鏈接,可以設置時間什麼的,如:

In [2]: import logging

In [3]: logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG)

In [4]: logging.warning('And this, too')
2016-12-06 15:40:43,577:WARNING:And this, too

進階使用

當想項目中使用logging模塊的時候肯定不能在這樣一句句的寫了,一般可能會抽象出一個模塊來,這樣比較有效一些。logging模塊提供了四個類(Loggers,Formatters,Filtters,Handlers)來實現不同的功能,與此對應的我們如果想封裝一個函數,也就要針對這幾個功能來自定義一下。

想自定義的話思路也很簡單,首先實例化一個相應的對象,然後進行一些設置,可以簡單看一下下麵的例子:

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

# 輸出是:
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
從配置文件導入配置

模塊內容:

import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

# 輸出
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

配置文件內容:

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

同時也可以使用YAML格式的配置文件,如:

version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  simpleExample:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console]

PS

Logging模塊使用也會有很多坑,常見的是日誌重覆列印的問題,大家可以搜一下,這裡提供一些鏈接供參考:

  1. http://www.jianshu.com/p/25f70905ae9d
  2. https://yinzo.github.io/14610807170718.html
  3. http://python.jobbole.com/86887/

參考

  1. https://docs.python.org/2/library/logging.html
  2. https://docs.python.org/2/howto/logging.html#logging-basic-tutorial
    

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • C++使用如下方法遍歷一個容器: 其中auto用到了C++11的類型推導。同時我們也可以使用std::for_each完成同樣的功能: 現在C++11的for迴圈有了一種新的用法: 上述方式是只讀,如果需要修改arr裡邊的值,可以使用for(auto& n:arr),for迴圈的這種使用方式的內在實 ...
  • 在用python的bottle框架開發時,前端使用ajax跨域訪問時,js代碼老是進入不了success,而是進入了error,而返回的狀態卻是200。url直接在瀏覽器訪問也是正常的,瀏覽器按F12後會發現下麵這個錯誤提示 通過搜索引擎查詢錯誤,會發現幾乎查找出來的答案都說是跨域問題,只需要在主文 ...
  • Django基本配置 Python的WEB框架有Django、Tornado、Flask 等多種,Django相較與其他WEB框架其優勢為:大而全,框架本身集成了ORM、模型綁定、模板引擎、緩存、Session等諸多功能 1、安裝 2、創建Django工程 其他命令: mysite目錄結構: Dja ...
  • 1.寫一條sql關聯兩個表要求顯示欄位如下 城市id 城市名稱=name 省份名稱=name select c.id,c.name,p.name from city as c join province as p on c.pid=p.id; 結果: 2.用thinkphp實現 關聯兩個表要求顯示字 ...
  • 博客一:轉載自http://shmilyaw-hotmail-com.iteye.com/blog/1825171 java stack的詳細實現分析 簡介 我們最常用的數據結構之一大概就是stack了。在實際的程式執行,方法調用的過程中都離不開stack。那麼,在一個成熟的類庫裡面,它的實現是怎麼 ...
  • 此篇文章同樣是參考SVNKit在wiki的官方文檔做的demo,每個類都可以單獨運行。具體的細節都寫到註釋里了~ 開發背景: SVNKit版本:1.7.14 附上官網下載鏈接:https://www.svnkit.com/org.tmatesoft.svn_1.7.14.standalone.zip ...
  • 1.demo中最常見的方式是在工程下的web.xml中設置(有時候根據業務可能需要設置action,在action中處理邏輯載入跳轉什麼的,比較少): 2.使用Urlrewrite地址重寫,優點還是挺多的,比如安全性能,具體可以百度下,下麵介紹使用方式: 首先還是導入 urlrewrite 的jar ...
  • 調用同步鎖的wait()、notify()、notifyAll()進行線程通信 看這個經典的存取款問題,要求兩個線程存款,兩個線程取款,賬戶里有餘額的時候只能取款,沒餘額的時候只能存款,存取款金額相同。相當於存取款交替進行,金額相同。 線程間通信,需要通過同一個同步監視器(也就是this或者顯式的O ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...