Python logging

Python logging

1、logging

  • 什麼是logging模塊

   通俗講就是:標準接口日誌模塊,用於記錄日誌python

  • logging日誌級別 - (默認級別是:warning)
    • debug     10 - 調試相信信息
    • info      20 - 信息
    • warning   30 - 警告信息. 出現一些不想出現的錯誤
    • error     40 - 嚴重錯誤. 某些功能出現錯誤
    • critical  50 - 嚴重錯誤. 程序沒法運行

     默認級別是warning網絡

import logging
   
#   默認是root用戶. 可進行修改的
logging.info("Test   info")
logging.debug("Test  debug")
logging.error("Test  error")
logging.warning("user [Harry] attempted wrong password more than 3 times")
logging.critical("server is down")
   
#    ps:以上命令在運行時.其中info and debug未打印出日誌.是由於日誌級別問題致使的.默認級別是warning.固然能夠進行自定義日誌級別
   
輸出:
ERROR:root:Test  error
WARNING:root:user [Harry] attempted wrong password more than 3 times
CRITICAL:root:server is down  
  • 將日誌寫入文件中
logging.basicConfig(filename='Harry.log',level=logging.WARNING)
logging.info("Test   info")
logging.debug("Test  debug")
logging.error("Test  error")
logging.warning("user [Harry] attempted wrong password more than 3 times")
logging.critical("server is down") 
  • 當level=logging.WARNING時。 那麼info and debug就不會打印,所以得出只會輸出大於和自己級別的日誌。 小於自己的日誌級別是不會打印的,可設置成DEBUG測試
    • filename表示日誌名稱。 level表示設置日誌級別(可進行更改) 
1 INFO:root:Test   info
2 DEBUG:root:Test  debug
3 ERROR:root:Test  error
4 WARNING:root:user [Harry] attempted wrong password more than 3 times
5 CRITICAL:root:server is down
6 ------------
7 ERROR:root:Test  error
8 WARNING:root:user [Harry] attempted wrong password more than 3 times
9 CRITICAL:root:server is down
Harry.log 
  • 日誌格式
%(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 用戶輸出的消息

需求一:app

  • 將日誌分別記錄在日誌裏面.並按照需求打印格式:【如:日誌中加時間、模塊、級別等相關信息】
import logging
  
logging.basicConfig(filename='Harry.log',
                    level=logging.WARNING,
                    #   此處分別是什麼意思.請查看日誌格式中的各類解釋
                    format='%(asctime)s %(filename)s:%(lineno)d:%(module)s:%(funcName)s - %(levelname)s: %(message)s',
                    datefmt='%Y/%d/%m %I:%M:%S %p')
logging.info("Test   info")
logging.debug("Test  debug")
logging.error("Test  error")
logging.warning("user [Harry] attempted wrong password more than 3 times")
logging.critical("server is down")
  
  
#   在函數中調用日誌模塊. 查看日誌區別
def Run_start():
    logging.warning("user [Harry] attempted wrong password more than 3 times")
  
Run_start()  
 1 2017/17/08 10:09:38 PM 11_logging_模塊.py - ERROR: Test  error
 2 2017/17/08 10:09:38 PM 11_logging_模塊.py - WARNING: user [Yuhonglin] attempted wrong password more than 3 times
 3 2017/17/08 10:09:38 PM 11_logging_模塊.py - CRITICAL: server is down
 4 2017/17/08 10:12:38 PM 11_logging_模塊.py:46 - ERROR: Test  error
 5 2017/17/08 10:12:38 PM 11_logging_模塊.py:47 - WARNING: user [Yuhonglin] attempted wrong password more than 3 times
 6 2017/17/08 10:12:38 PM 11_logging_模塊.py:48 - CRITICAL: server is down
 7 2017/17/08 10:14:13 PM 11_logging_模塊.py:46:11_logging_模塊 - ERROR: Test  error
 8 2017/17/08 10:14:13 PM 11_logging_模塊.py:47:11_logging_模塊 - WARNING: user [Yuhonglin] attempted wrong password more than 3 times
 9 2017/17/08 10:14:13 PM 11_logging_模塊.py:48:11_logging_模塊 - CRITICAL: server is down
10 2017/17/08 10:15:05 PM 11_logging_模塊.py:46:11_logging_模塊:<module> - ERROR: Test  error
11 2017/17/08 10:15:05 PM 11_logging_模塊.py:47:11_logging_模塊:<module> - WARNING: user [Yuhonglin] attempted wrong password more than 3 times
12 2017/17/08 10:15:05 PM 11_logging_模塊.py:48:11_logging_模塊:<module> - CRITICAL: server is down
13 2017/17/08 10:15:42 PM 11_logging_模塊.py:46:11_logging_模塊:<module> - ERROR: Test  error
14 2017/17/08 10:15:42 PM 11_logging_模塊.py:47:11_logging_模塊:<module> - WARNING: user [Yuhonglin] attempted wrong password more than 3 times
15 2017/17/08 10:15:42 PM 11_logging_模塊.py:48:11_logging_模塊:<module> - CRITICAL: server is down
16 2017/17/08 10:15:42 PM 11_logging_模塊.py:52:11_logging_模塊:Run_start - WARNING: user [Yuhonglin] attempted wrong password more than 3 times
Harry.log 

需求二:ide

  • 如何同時將log打印在屏幕和文件日誌裏.?
  • Python 使用logging模塊記錄日誌涉及四個主要類,使用官方文檔中的歸納最爲合適:    
    • logger:  提供了應用程序能夠直接使用的接口;
    • handler: 將(logger建立的)日誌記錄發送到合適的目的輸出;
    • filter:  提供了細度設備來決定輸出哪條日誌記錄;
    • formatter:決定日誌記錄的最終輸出格式。
  • logger

   1.每一個程序在輸出信息以前都要得到一個Logger。Logger一般對應了程序的模塊名,好比聊天工具的圖形界面模塊能夠這樣得到它的Logger:
     LOG=logging.getLogger(」chat.gui」)
   2.而核心模塊能夠這樣:
     LOG=logging.getLogger(」chat.kernel」)函數

     Logger.setLevel(lel):指定最低的日誌級別,低於lel的級別將被忽略。debug是最低的內置級別,critical爲最高
     Logger.addFilter(filt)、Logger.removeFilter(filt):添加或刪除指定的filter
     Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增長或刪除指定的handler
     Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():能夠設置的日誌級別工具

  • handler

   1.handler對象負責發送相關的信息到指定目的地。Python的日誌系統有多種Handler可使用。有些Handler能夠把信息輸出到控制檯,有些Logger能夠把信息輸出到文件,還有些    Handler能夠把信息發送到網絡上。若是以爲不夠用,還能夠編寫本身的Handler。能夠經過addHandler()方法添加多個多handler
     Handler.setLevel(lel):指定被處理的信息級別,低於lel級別的信息將被忽略
     Handler.setFormatter():給這個handler選擇一個格式
     Handler.addFilter(filt)、Handler.removeFilter(filt):新增或刪除一個filter對象post

  • 每一個Logger能夠附加多個Handler。接下來咱們就來介紹一些經常使用的Handler:

   1) logging.StreamHandler
      使用這個Handler能夠向相似與sys.stdout或者sys.stderr的任何文件對象(file object)輸出信息。它的構造函數是:
      StreamHandler([strm])
      其中strm參數是一個文件對象。默認是sys.stderr測試

   2) logging.FileHandler
      和StreamHandler相似,用於向一個文件輸出日誌信息。不過FileHandler會幫你打開這個文件。它的構造函數是:
      FileHandler(filename[,mode])
      filename是文件名,必須指定一個文件名。
      mode是文件的打開方式。參見Python內置函數open()的用法。默認是’a',即添加到文件末尾。ui

   3) logging.handlers.RotatingFileHandler
      這個Handler相似於上面的FileHandler,可是它能夠管理文件大小。當文件達到必定大小以後,它會自動將當前日誌文件更名,而後建立 一個新的同名日誌文件繼續輸出。好比日誌文件是chat.log。當chat.log達到指定的大小以後,RotatingFileHandler自動把 文件更名爲chat.log.1。不過,若是chat.log.1已經存在,會先把chat.log.1重命名爲chat.log.2。。。最後從新建立 chat.log,繼續輸出日誌信息。它的構造函數是:
      RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
      其中filename和mode兩個參數和FileHandler同樣。
      maxBytes用於指定日誌文件的最大文件大小。若是maxBytes爲0,意味着日誌文件能夠無限大,這時上面描述的重命名過程就不會發生。
      backupCount用於指定保留的備份文件的個數。好比,若是指定爲2,當上面描述的重命名過程發生時,原有的chat.log.2並不會被改名,而是被刪除。spa

   4) logging.handlers.TimedRotatingFileHandler
      這個Handler和RotatingFileHandler相似,不過,它沒有經過判斷文件大小來決定什麼時候從新建立日誌文件,而是間隔必定時間就 自動建立新的日誌文件。重命名的過程與RotatingFileHandler相似,不過新的文件不是附加數字,而是當前時間。它的構造函數是:
      TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
      其中filename參數和backupCount參數和RotatingFileHandler具備相同的意義。
      interval是時間間隔。
      when參數是一個字符串。表示時間間隔的單位,不區分大小寫。它有如下取值:
      S 秒
      M 分
      H 小時
      D 天
      W 每星期(interval==0時表明星期一)
      midnight 天天凌晨

  • 日誌屏幕正常打印並寫在文件中:
import logging
#   create logger   TEST-LOG表示建立日誌的名字.
logger = logging.getLogger('TEST-LOG')
#   設置DEBUG級別.可修改爲其餘.
logger.setLevel(logging.DEBUG)

#   create console handler and set level to debug
#   建立handler 和設置日誌級別.
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)

#   create file handler and set level to warning
#   建立文件handler 和設置級別
fh = logging.FileHandler("Access.log",encoding="utf-8")
fh.setLevel(logging.ERROR)
#   以上建立了兩個handler
#   定義日誌格式fh_formatter 輸入文件中格式  ch_formatter輸入屏幕日誌格式
fh_formatter = logging.Formatter('%(asctime)s %(filename)s:%(lineno)d:%(module)s: - %(levelname)s: %(message)s')
ch_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

#   add formatter to ch and fh.
fh.setFormatter(fh_formatter)
ch.setFormatter(ch_formatter)

#   add ch and fh to logger
#   告訴log往那裏輸出.
logger.addHandler(fh)
logger.addHandler(ch)

logger.warning("Warning commint.............")
logger.error("errors  happend...............")  

       

需求三:  

 1 import logging
 2 
 3 from logging import handlers
 4 
 5 logger = logging.getLogger('TEST')
 6 
 7 #   定義日誌名稱
 8 log_file = "TimeOut.log"
 9 #   maxBytes定義文件中字節數    backupCount最多保留三個
10 fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3,encoding="utf-8")
11 
12 #   定義日誌格式
13 formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')
14 
15 fh.setFormatter(formatter)
16 
17 logger.addHandler(fh)
18 
19 logger.warning("test1")
20 logger.warning("test12")
21 logger.warning("test13")
22 logger.warning("test14")
23 logger.warning("test15")
24 logger.warning("test16")
25 logger.warning("test17")
日誌文件自動截斷_運行看效果  
 1 import logging
 2 
 3 from logging import handlers
 4 
 5 logger = logging.getLogger('TEST')
 6 
 7 #   定義日誌名稱
 8 log_file = "TimeOut.log"
 9 
10 #   按時間生成.when表示秒 對應的S可修改爲D等其餘的.
11 fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3,encoding="utf-8")
12 
13 #   定義日誌格式
14 formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')
15 
16 fh.setFormatter(formatter)
17 
18 logger.addHandler(fh)
19 import time
20 
21 logger.warning("test1")
22 time.sleep(2)
23 logger.warning("test12")
24 time.sleep(2)
25 logger.warning("test13")
26 logger.warning("test14")
27 time.sleep(2)
28 logger.warning("test15")
29 logger.warning("test16")
日誌文件按時間自動生成_運行看效果
相關文章
相關標籤/搜索