python中logging模塊的使用


一、基本用法

  只需要基本的配置,就可以使用了。

import logging

def fun2():
    logging.basicConfig(filename="fun2.log",format="%(asctime)s %(message)s",level=logging.DEBUG)
    logging.debug("this is fun2 log")

 

二、進行詳細配置

  首先添加一個fileHandler來配置記錄的文件,Formatter來設置記錄的格式和時間的格式,getLogger是獲得一個指定名字記錄器,然后給這個logger添加handler,並設置記錄級別,然后可以用相應的級別進行記錄了。

import logging

def fun1():
    
    logname = "test.log"
    filehandler = logging.FileHandler(filename=logname,encoding="utf-8")
    fmter = logging.Formatter(fmt="%(asctime)s %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
    filehandler.setFormatter(fmter)
    loger = logging.getLogger(__name__)
    loger.addHandler(filehandler)
    loger.setLevel(logging.FATAL)
    loger.fatal("second log")

 

其中Formatter配置參數fmt有如下可選參數

  %(name)s            Name of the logger (logging channel)
    %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
                        WARNING, ERROR, CRITICAL)
    %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
                        "WARNING", "ERROR", "CRITICAL")
    %(pathname)s        Full pathname of the source file where the logging
                        call was issued (if available)
    %(filename)s        Filename portion of pathname
    %(module)s          Module (name portion of filename)
    %(lineno)d          Source line number where the logging call was issued
                        (if available)
    %(funcName)s        Function name
    %(created)f         Time when the LogRecord was created (time.time()
                        return value)
    %(asctime)s         Textual time when the LogRecord was created
    %(msecs)d           Millisecond portion of the creation time
    %(relativeCreated)d Time in milliseconds when the LogRecord was created,
                        relative to the time the logging module was loaded
                        (typically at application startup time)
    %(thread)d          Thread ID (if available)
    %(threadName)s      Thread name (if available)
    %(process)d         Process ID (if available)
    %(message)s         The result of record.getMessage(), computed just as
                        the record is emitted

 

以下皆轉自Python logging模塊詳解

 三、額外說明

  1 可供選擇的日志級別有

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

  Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical()輸出不同級別的日志,只有日志等級大於或等於設置的日志級別的日志才會被輸出。

  2 Handler

    Handler對象負責發送相關的信息到指定目的地,常用方法如下

    Handler.setLevel(lel):指定日志級別,低於lel級別的日志將被忽略
    Handler.setFormatter():給這個handler選擇一個Formatter
    Handler.addFilter(filt)、Handler.removeFilter(filt):新增或刪除一個filter對象

  可以通過addHandler()方法為Logger添加多個Handler

logging.handlers.RotatingFileHandler 類似於上面的FileHandler,但是它可以管理文件大小。當文件達到一定大小之后,它會自動將當前日志文件改名,然后創建一個新的同名日志文件繼續輸出
logging.handlers.TimedRotatingFileHandler 和RotatingFileHandler類似,不過,它沒有通過判斷文件大小來決定何時重新創建日志文件,而是間隔一定時間就自動創建新的日志文件
logging.handlers.SocketHandler 使用TCP協議,將日志信息發送到網絡。
logging.handlers.DatagramHandler 使用UDP協議,將日志信息發送到網絡。
logging.handlers.SysLogHandler 日志輸出到syslog
logging.handlers.NTEventLogHandler 遠程輸出日志到Windows NT/2000/XP的事件日志 
logging.handlers.SMTPHandler 遠程輸出日志到郵件地址
logging.handlers.MemoryHandler 日志輸出到內存中的制定buffer
logging.handlers.HTTPHandler 通過"GET"或"POST"遠程輸出到HTTP服務器

  各個Handler的具體用法可查看參考書冊:

  https://docs.python.org/2/library/logging.handlers.html#module-logging.handlers

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM