Python日誌(logging)模組使用方法簡介

來源:互聯網
上載者:User

標籤:logging python

介紹

A logger is configured to have a log level. This log level describes the severity of the messages that the logger will handle. Python defines the following log levels:

§ DEBUG: Low level system information for debugging purposes§ INFO: General system information§ WARNING: Information describing a minor problem that has occurred.§ ERROR: Information describing a major problem that has occurred.§ CRITICAL: Information describing a critical problem that has occurred.

Each message that is written to the logger is a Log Record. Each log record also has a log level indicating the severity of that specific message. A log record can also contain useful metadata that describes the event that is being logged. This can include details such as a stack trace or an error code.

When a message is given to the logger, the log level of the message is compared to the log level of the logger. If the log level of the message meets or exceeds the log level of the logger itself, the message will undergo further processing. If it doesn’t, the message will be ignored.

Once a logger has determined that a message needs to be processed, it is passed to a Handler.

(來源:https://docs.djangoproject.com/en/1.4/topics/logging/ )

簡單的範例

#-- coding: utf-8 --

import logging

"""logging的簡單使用樣本

"""

if __name__ == ‘__main__‘:# 最簡單的用法,不推薦直接用logging模組logging.debug(u‘這個不會被列印出來‘)logging.info(u‘這個也不會被列印出來‘)logging.warning(u‘這個就會了,因為logging預設的層級是WARNING,低於這個等級的資訊就會被忽略‘)

稍微難一點的範例

#-*- coding: utf-8 -*-import logging"""logging的使用樣本"""if __name__ == ‘__main__‘:        # python官方文檔中提供的一段樣本,使用logging模組產生logger對象        FORMAT = ‘%(asctime)-15s %(clientip)s %(user)-8s %(message)s‘        logging.basicConfig(format = FORMAT)        d = { ‘clientip‘ : ‘192.168.0.1‘, ‘user‘ : ‘fbloggs‘ }        # 建立一個日誌對象        logger = logging.getLogger(‘tcpserver‘)        logger.warning(‘Protocol problem: %s‘, ‘connection reset‘, extra = d)        # 順位        logger.setLevel(logging.DEBUG)           logger.debug(‘Hello‘, extra = d)

複雜一點的用法,為logger添加了若干個handler。

#-*- coding: utf-8 -*-import logging, logging.config"""logging的使用樣本"""if __name__ == ‘__main__‘:        # 比較複雜的用法        LOGGING = {                             # 版本,總是1                             ‘version‘: 1,                             ‘disable_existing_loggers‘: True,                             ‘formatters‘: {                                                            ‘verbose‘: {‘format‘: ‘%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s‘},                                                             ‘simple‘: {‘format‘: ‘%(levelname)s %(message)s‘},                                                             ‘default‘: {                                                                                     ‘format‘ : ‘%(asctime)s %(message)s‘,                                                                                     ‘datefmt‘ : ‘%Y-%m-%d %H:%M:%S‘                                                                }                                },                             ‘handlers‘: {                                                        ‘null‘: {                                                                         ‘level‘:‘DEBUG‘,                                                                         ‘class‘:‘logging.NullHandler‘,                                                        },                                                        ‘console‘:{                                                                             ‘level‘:‘DEBUG‘,                                                                             ‘class‘:‘logging.StreamHandler‘,                                                                             ‘formatter‘: ‘default‘                                                        },                                                        ‘file‘: {                                                                         ‘level‘: ‘INFO‘,                                                                         # TimedRotatingFileHandler會將日誌按一定時間間隔寫入檔案中,並                                                                         # 將檔案重新命名為‘原檔案名稱+時間戮‘這樣的形式                                                                         # Python提供了其它的handler,參考logging.handlers                                                                         ‘class‘: ‘logging.handlers.TimedRotatingFileHandler‘,                                                                         ‘formatter‘: ‘default‘,                                                                         # 後面這些會以參數的形式傳遞給TimedRotatingFileHandler的                                                                         # 構造器                                                                         # filename所在的目錄要確儲存在                                                                         ‘filename‘ : ‘log‘,                                                                         # 每5分鐘重新整理一下                                                                         ‘when‘ : ‘M‘,                                                                         ‘interval‘ : 1,                                                                         ‘encoding‘ : ‘utf8‘,                                                        }                                },                             ‘loggers‘ : {                                                        # 定義了一個logger                                                        ‘mylogger‘ : {                                                                                    ‘level‘ : ‘DEBUG‘,                                                                                    ‘handlers‘ : [‘console‘, ‘file‘],                                                                                    ‘propagate‘ : True                                                        }                                }         }        logging.config.dictConfig(LOGGING)        logger = logging.getLogger(‘mylogger‘)        logger.info(‘Hello‘)

另外,還可以通過設定檔來配置logging,方法如下:

設定檔(log_conf):

[loggers]keys=root,mylogger[handlers]keys=null,console,file[formatters]keys=verbose,simple,default[formatter_verbose]format=%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)sdatefmt=class=logging.Formatter[formatter_simple]format=%(levelname)s %(message)sdatefmt=class=logging.Formatter[formatter_default]format=%(asctime)s %(message)sdatefmt=%Y-%m-%d %H:%M:%Sclass=logging.Formatter[logger_mylogger]level=DEBUGhandlers=console,filepropagate=1qualname=[logger_root]level=NOTSEThandlers=[handler_null]class=NullHandlerlevel=DEBUGargs=()[handler_console]class=StreamHandlerlevel=DEBUGargs=()[handler_file]class=handlers.TimedRotatingFileHandlerlevel=INFOformatter=defaultargs=(‘log‘,‘M‘,1,0,‘utf8‘)

Python代碼:

#-*- coding: utf-8 -*-import logging, logging.config"""logging的使用樣本"""if __name__ == ‘__main__‘:        # 使用設定檔        logging.config.fileConfig(‘log_conf‘)        logger = logging.getLogger(‘mylogger‘)        logger.info(‘Hello‘)

Python日誌(logging)模組使用方法簡介

聯繫我們

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