python的logging日誌模組(二)__python

來源:互聯網
上載者:User

晚上比較懶,直接搬磚了。

1.簡單的將日誌列印到螢幕  

import logging

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

 

螢幕上列印:
WARNING:root:This is warning message

預設情況下,logging將日誌列印到螢幕,記錄層級為WARNING;
記錄層級大小關係為:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,當然也可以自己定義記錄層級。 2.通過logging.basicConfig函數對日誌的輸出格式及方式做相關配置

import logging

logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='myapp.log',
                filemode='w')
    
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

 

./myapp.log檔案中內容為:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig函數各參數:
filename: 指定記錄檔名
filemode: 和file函數意義相同,指定記錄檔的開啟模式,'w'或'a'
format: 指定輸出的格式和內容,format可以輸出很多有用資訊,如上例所示:
 %(levelno)s: 列印記錄層級的數值
 %(levelname)s: 列印記錄層級名稱
 %(pathname)s: 列印當前執行程式的路徑,其實就是sys.argv[0]
 %(filename)s: 列印當前執行程式名
 %(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被忽略 3.將日誌同時輸出到檔案和螢幕

import logging

logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='myapp.log',
                filemode='w')

#################################################################################################
#定義一個StreamHandler,將INFO層級或更高的日誌資訊列印到標準錯誤,並將其添加到當前的Tlog對象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

 

螢幕上列印:
root        : INFO     This is info message
root        : WARNING  This is warning message

./myapp.log檔案中內容為:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging之日誌復原

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有一個Tlog的主對象,其它處理方式都是通過addHandler添加進去的。
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伺服器

 

由於StreamHandler和FileHandler是常用的Tlog方式,所以直接包含在logging模組中,而其他方式則包含在logging.handlers模組中,
上述其它處理方式的使用請參見python2.5手冊。 5.通過logging.config模組配置日誌

#logger.conf

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

[loggers]
keys=root,example01,example02

[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

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

[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)

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

[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=

上例3:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

上例4:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

6.logging是安全執行緒的

from:http://blog.csdn.NET/yatere/article/details/6655445

原文地址:Python 模組 Logging HOWTO 官方文檔 一、Logging簡介

Logging是一種當軟體運行時對事件的追蹤記錄方式,軟體開發人員通過在代碼中調用Logging的相關方法來提示某些事件的發生。事件可以通過描述資訊描述,當然描述資訊中也可以包含變數,因為對於事件的每次觸發,描述資訊可能不同。 二、簡單的例子

一個簡單的例子:

import logginglogging.warning('Watch out!')  # 資訊會列印到控制台logging.info('I told you so')  # 不會列印任何資訊,因為預設層級高於info

如果你將上述代碼存入Python檔案,然後運行:

WARNING:root:Watch out!

INFO的資訊沒有出現在控制台,因為預設的層級為WARNING高於INFO。日誌資訊包含記錄層級和事件描述資訊,暫且別太在意輸出中的root,稍後會有介紹。實際的輸出可以讓你任意的定製,格式設定會在稍後介紹。 三、將日誌資訊存入檔案

在應用中我們常常需要將日誌資訊存入檔案。請重新建立一個新檔案,不要接在上面的python檔案中。

import logginglogging.basicConfig(filename='example.log',level=logging.DEBUG)logging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')

運行他,然後會產生一個記錄檔example.log,開啟它就能看到具體的日誌資訊:

DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too

在這個例子中,我們看到了如何設定記錄層級,這是一個閾值,用於控制日誌的輸出。
如果你想要通過命令列來設定記錄層級,你可以這樣做:

--log=INFO

並且 你也可以擷取傳遞給–log的參數,你可以這樣做:

getattr(logging, loglevel.upper())

你可以通過basicConfig()方法來設定記錄層級——傳遞level參數。你可能想要檢查level參數值的合法性,可以像下面這樣:

# assuming loglevel is bound

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.