python: 不同層級的日誌輸出到不同檔案的日誌類

來源:互聯網
上載者:User
#!/usr/bin/env python# -*- coding: utf-8 -*-'''該日誌類可以把不同層級的日誌輸出到不同的記錄檔中'''import osimport sysimport timeimport loggingimport inspecthandlers = {logging.NOTSET:"/tmp/TNLOG-notset.log",            logging.DEBUG:"/tmp/TNLOG-debug.log",            logging.INFO:"/tmp/TNLOG-info.log",            logging.WARNING:"/tmp/TNLOG-warning.log",            logging.ERROR:"/tmp/TNLOG-error.log",            logging.CRITICAL:"/tmp/TNLOG-critical.log"}def createHandlers():    logLevels = handlers.keys()    for level in logLevels:        path = os.path.abspath(handlers[level])        handlers[level] = logging.FileHandler(path)#載入模組時建立全域變數createHandlers()class TNLog(object):    def printfNow(self):        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())        def __init__(self,level=logging.NOTSET):        self.__loggers = {}        logLevels = handlers.keys()        for level in logLevels:            logger = logging.getLogger(str(level))            #如果不指定level,獲得的handler似乎是同一個handler?            logger.addHandler(handlers[level])            logger.setLevel(level)            self.__loggers.update({level:logger})    def getLogMessage(self,level,message):        frame,filename,lineNo,functionName,code,unknowField = inspect.stack()[2]        '''日誌格式:[時間] [類型] [記錄代碼] 資訊'''        return "[%s] [%s] [%s - %s - %s] %s" %(self.printfNow(),level,filename,lineNo,functionName,message)        def info(self,message):        message = self.getLogMessage("info",message)        self.__loggers[logging.INFO].info(message)        def error(self,message):        message = self.getLogMessage("error",message)        self.__loggers[logging.ERROR].error(message)        def warning(self,message):        message = self.getLogMessage("warning",message)        self.__loggers[logging.WARNING].warning(message)        def debug(self,message):        message = self.getLogMessage("debug",message)        self.__loggers[logging.DEBUG].debug(message)        def critical(self,message):        message = self.getLogMessage("critical",message)        self.__loggers[logging.CRITICAL].critical(message)if __name__ == "__main__":    logger = TNLog()    logger.debug("debug")    logger = TNLog()    logger.info("info")    logger = TNLog()    logger.warning("warning")    logger = TNLog()    logger.error("error")    logger = TNLog()    logger.critical("critical")
相關文章

聯繫我們

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