1. 程式人生 > 其它 >Python 封裝使用日誌處理類

Python 封裝使用日誌處理類

技術標籤:python類logging

  • 在logging的基礎上封裝一個簡易的日誌處理類,同時輸出到日誌檔案和列印到螢幕
#coding=utf-8
import logging
import logging.handlers

class Log:
    __file = 'log.log'#日誌檔名稱
    __handler = False
    __fmt = '%(asctime)s - %(filename)s:[line:%(lineno)s] - %(name)s - %(message)s'#輸出格式

    def __init__(self):
         logging.
basicConfig(filename=self.__file, filemode='a+', format=self.__fmt) # self.__handler = logging.handlers.RotatingFileHandler(self.__file, maxBytes=1024*1024, backupCount=5) #列印 self.__handler = logging.StreamHandler() self.__handler.setLevel(logging.INFO) #設定格式 formatter =
logging.Formatter(self.__fmt) self.__handler.setFormatter(formatter) return #獲取例項 def getInstance(self, strname): logger = logging.getLogger(strname) logger.addHandler(self.__handler) logger.setLevel(logging.DEBUG) return logger
  • 使用demo
if __name__==
"__main__": testlog = Log().getInstance("test") testlog.info("info log") testlog.debug("debug log") testlog.warning("waring log")

原創僅僅學會簡單,原部落格here