python logging類庫使用例子_python

來源:互聯網
上載者:User

一、簡單使用

複製代碼 代碼如下:

def TestLogBasic():
    import logging
    logging.basicConfig(filename = 'log.txt', filemode = 'a', level = logging.NOTSET, format = '%(asctime)s - %(levelname)s: %(message)s')
    logging.debug('this is a message')
    logging.info("this is a info")
    logging.disable(30)#logging.WARNING
    logging.warning("this is a warnning")
    logging.critical("this is a critical issue")
    logging.error("this is a error")
    logging.addLevelName(88,"MyCustomError")
    logging.log(88,"this is an my custom error")
    try:
      raise Exception('this is a exception')
    except:
      logging.exception( 'exception')
    logging.shutdown()

TestLogBasic()

說明:(此執行個體為最簡單的用法,用來將log記錄到log檔案中)

1)logging.basicConfig()中定義預設的log到log.txt,log檔案為append模式,處理所有的level大於logging.NOTSET的logging,log的格式定義為'%(asctime)s - %(levelname)s: %(message)s';

2)使用logging.debug()...等來log相應level的log;

3)使用logging.disable()來disable某個logging level;

4)使用logging.addLevelName增加自訂的logging level;

5)使用logging.log來log自訂的logging level的log;

輸出的text的log如下:

複製代碼 代碼如下:

2011-01-18 10:02:45,415 - DEBUG: this is a message
2011-01-18 10:02:45,463 - INFO: this is a info
2011-01-18 10:02:45,463 - CRITICAL: this is a critical issue
2011-01-18 10:02:45,463 - ERROR: this is a error
2011-01-18 10:02:45,463 - MyCustomError: this is an my custom error
2011-01-18 10:02:45,463 - ERROR: exception
Traceback (most recent call last):
  File "testlog.py", line 15, in TestLogBasic
    raise Exception('this is a exception')
Exception: this is a exception

二、logging的level

複製代碼 代碼如下:

#logging level
#logging.NOTSET 0
#logging.DEBUG 10
#logging.INFO 20
#logging.WARNING 30
#logging.ERROR 40
#logging.CRITICAL 50

logging的level對應於一個int,例如10,20...使用者可以自訂logging的level。

可以使用logging.setLevel()來指定要處理的logger層級,例如my_logger.setLevel(logging.DEBUG)表示只處理logging的level大於10的logging。
 

三、Handlers

Handler定義了log的儲存和顯示方式。

NullHandler不做任何事情。

StreamHandler執行個體發送錯誤到流(類似檔案的對象)。
FileHandler執行個體發送錯誤到磁碟檔案。
BaseRotatingHandler是所有輪徇日誌的基類,不能直接使用。但是可以使用RotatingFileHandler和TimeRotatingFileHandler。
RotatingFileHandler執行個體發送資訊到磁碟檔案,並且限制最大的記錄檔大小,並適時輪徇。
TimeRotatingFileHandler執行個體發送錯誤資訊到磁碟,並在適當的事件間隔進行輪徇。
SocketHandler執行個體發送日誌到TCP/IP socket。
DatagramHandler執行個體發送錯誤資訊通過UDP協議。
SMTPHandler執行個體發送錯誤資訊到特定的email地址。
SysLogHandler執行個體發送日誌到UNIX syslog服務,並支援遠程syslog服務。
NTEventLogHandler執行個體發送日誌到WindowsNT/2000/XP事件記錄。
MemoryHandler執行個體發送日誌到記憶體中的緩衝區,並在達到特定條件時清空。
HTTPHandler執行個體發送錯誤資訊到HTTP伺服器,通過GET或POST方法。
NullHandler,StreamHandler和FileHandler類都是在核心logging模組中定義的。其他handler定義在各個子模組中,叫做logging.handlers。

當然還有一個logging.config模組提供了配置功能。

四、FileHandler + StreamHandler

複製代碼 代碼如下:

def TestHanderAndFormat():
    import logging
    logger = logging.getLogger("simple")
    logger.setLevel(logging.DEBUG)
   
    # create file handler which logs even debug messages
    fh = logging.FileHandler("simple.log")
    fh.setLevel(logging.DEBUG)
   
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
   
    # create formatter and add it to the handlers
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
   
    # add the handlers 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("critical message")

TestHanderAndFormat()

說明:(此執行個體同時使用FileHandler和StreamHandler來實現同時將log寫到檔案和console)

1)使用logging.getLogger()來建立命名logger;

2)使用logging.FileHandler()來產生FileHandler來將log寫入log檔案,使用logger.addHandler()將handler與logger綁定;

3)使用logging.StreamHandler()來產生StreamHandler來將log寫到console,使用logger.addHandler()將handler與logger綁定;

4)使用logging.Formatter()來構造log格式的執行個體,使用handler.setFormatter()來將formatter與handler綁定;

 運行結果

simple.txt

複製代碼 代碼如下:

2011-01-18 11:25:57,026 - simple - DEBUG - debug message
2011-01-18 11:25:57,072 - simple - INFO - info message
2011-01-18 11:25:57,072 - simple - WARNING - warn message
2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

console

複製代碼 代碼如下:

2011-01-18 11:25:57,072 - simple - ERROR - error message
2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

五、RotatingFileHandler

複製代碼 代碼如下:

def TestRotating():
    import glob
    import logging
    import logging.handlers
   
    LOG_FILENAME = 'logging_rotatingfile_example.out'

    # Set up a specific logger with our desired output level
    my_logger = logging.getLogger('MyLogger')
    my_logger.setLevel(logging.DEBUG)

    # Add the log message handler to the logger
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)

    my_logger.addHandler(handler)

    # Log some messages
    for i in range(20):
        my_logger.debug('i = %d' % i)

    # See what files are created
    logfiles = glob.glob('%s*' % LOG_FILENAME)

    for filename in logfiles:
        print(filename)
       
TestRotating()

說明:

RotatingFileHandler指定了單個log檔案的size的最大值和log檔案的數量的最大值,如果檔案大於最大值,將分割為多個檔案,如果log檔案的數量多於最多個數,最老的log檔案將被刪除。例如此例中最新的log總是在logging_rotatingfile_example.out,logging_rotatingfile_example.out.5中包含了最老的log。

運行結果:

複製代碼 代碼如下:

logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5

六、使用fileConfig來使用logger

複製代碼 代碼如下:

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")

logging.conf檔案如下:

複製代碼 代碼如下:

[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
datefmt=

運行結果:

複製代碼 代碼如下:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.