logging是Python自帶的日誌系統, 使用方便靈活.python
示例, 將警告輸出到終端:服務器
>>>import logging >>>logging.warning('This is warning message') WARNING:root:This is warning message
咱們能夠自定義logger來向文件和終端寫日誌, 並重設了日誌的格式:app
import logging logger = logging.getLogger("service log") logger.setLevel(logging.DEBUG) fh = logging.FileHandler('log/info.log', 'a') fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S") fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch)
寫入日誌:函數
>>>logger.info("admin login success") 2017-02-21 11:58:42 - service log - INFO - admin login success
logging模塊主要提供了四個類:spa
logger提供了應用程序能夠直接使用的接口;線程
handler將(logger建立的)日誌記錄發送到合適的輸出通道;debug
filter決定輸出哪條日誌記錄;日誌
formatter決定日誌記錄的最終輸出格式;code
這裏提供一個orm
logger默認提供5個級別的日誌輸出, 從高到低爲:
logger.critical(msg)
logger.error(msg)
logger.warning(msg)
logger.info(msg)
logger.debug(msg)
logger只輸出高於或等於當前級別的日誌, logging的root logger默認級別爲info.
>>> log = logging.getLogger() >>> log.setLevel(logging.INFO) >>> logging.INFO 20
logger能夠添加handler, filter和formatter以加強功能:
Logger.addHandler(handler)
Logger.removeHandler(handler)
Logger.addFilter(filter)
Logger.removeFilter(filter)
Handler把Logger記錄發到相應的通道, logging中提供了經常使用的幾個Handler:
StreamHandler 發送日誌到終端輸出流中
FileHandler 發送日誌到日誌文件中
NullHandler 無操做的日誌處理類
將日誌輸出到文件:
>>> logger = logging.getLogger() >>> fh = logging.FileHandler('test.log', 'w') >>> logger.addHandler(fh) >>> logger.warning('This is warning message') WARNING:root:This is warning message ~$ cat test.log This is warning message
其它的Handlers在logging.handlers中:
Formatter對象設置日誌信息的格式, 示例:
>>> logger = logging.getLogger() >>> handler = logging.StreamHandler() >>> formatter = logging.Formatter('%(name)-6s: %(levelname)-8s %(asctime)-8s %(message)s') >>> handler.setFormatter(formatter) >>> logger.addHandler(handler) >>> logger.warning('This is warning message') WARNING:root:This is warning message root : WARNING 2016-06-07 21:48:57,801 This is warning message
第二行信息即爲新增Formatter輸出的沒,這裏沒有移除原有Formatter因此輸出了兩條信息.
Formatter的標識符以下表所示:
%(name)s |
Logger的名字 |
%(levelno)s |
數字形式的日誌級別 |
%(levelname)s |
文本形式的日誌級別 |
%(pathname)s |
調用日誌輸出函數的模塊的完整路徑名,可能沒有 |
%(filename)s |
調用日誌輸出函數的模塊的文件名 |
%(module)s |
調用日誌輸出函數的模塊名 |
%(funcName)s |
調用日誌輸出函數的函數名 |
%(lineno)d |
調用日誌輸出函數的語句所在的代碼行 |
%(created)f |
當前時間,用UNIX標準的表示時間的浮 點數表示 |
%(relativeCreated)d |
輸出日誌信息時的,自Logger建立以 來的毫秒數 |
%(asctime)s |
字符串形式的當前時間。默認格式是 「2003-07-08 16:49:45,896」。逗號後面的是毫秒 |
%(thread)d |
線程ID。可能沒有 |
%(threadName)s |
線程名。可能沒有 |
%(process)d |
進程ID。可能沒有 |
%(message)s |
用戶輸出的消息 |
logging.getLogger()時參數的格式相似於「A.B.C」, 這樣作也便於Filter的配置.名爲「A.B」的過濾器只讓名字帶有 「A.B」前綴的Logger輸出信息.
>>>import logging >>>logger = logging.getLogger('cn.finley') >>>handler = logging.StreamHandler() >>>filter = logging.Filter('cn.finley') >>>handler.addFilter(filter) >>>logger.addHandler(handler) >>>logger.warning('This is warning message') >>> >>>fake_logger = logging.getLogger('cn.fakefinley') >>>handler = logging.StreamHandler() >>>filter = logging.Filter('cn.finley') >>>handler.addFilter(filter) >>>fake_logger.addHandler(handler) >>>fake_logger.warning('This is warning message') This is warning message
能夠看到fake_logger
的輸出被攔截
logging模塊提供了root logger.
logging模塊也提供了一系列模塊方法:
logging.getLogger([name]) 根據config返回指定的logger, 默認返回root logger
logging.basicConfig(): 用默認Formatter爲日誌系統創建一個StreamHandler,設置baseConfig並加到root logger中
logging.debug(), logging.info(), logging.warning(), logging.error()、logging.critical()能夠直接經過root logger輸出日誌信息.
basicConfig方法提供對RootHandler的基本配置,示例:
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.config模塊能夠經過文件配置logger, 先展現配置文件:
#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=
使用.conf文件配置logger:
>>> 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') example01 : INFO This is info message >>> logger.warning('This is warning message') example01 : WARNING This is warning message