1. 程式人生 > >Python logger模組應用示例

Python logger模組應用示例

同時輸出到檔案和終端,並設定不同的輸出級別

#! /usr/bin/env python
# coding: utf-8
import os
import logging

class MyLogger(logging.Logger):
    def __init__(self, filename='log/test.log'):
        # super(MyLogger, self).__init__(filename)
        logging.Logger.__init__(self, filename)

        # 設定日誌格式
        fmtHandler = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)s][%(levelname)s] %(message)s')

        # 終端log輸出流設定
        try:
            consoleHd = logging.StreamHandler()
            consoleHd.setLevel(logging.ERROR)
            consoleHd.setFormatter(fmtHandler)
            self.addHandler(consoleHd)
        except Exception as reason:
            self.error("%s" % reason)

        # 設定log檔案
        try:
            os.makedirs(os.path.dirname(filename))
        except Exception as reason:
            pass
        try:
            fileHd = logging.FileHandler(filename)
            fileHd.setLevel(logging.INFO)
            fileHd.setFormatter(fmtHandler)
            self.addHandler(fileHd)
        except Exception as reason:
            self.error("%s" % reason)            

        return
        # 設定回滾日誌,每個日誌最大10M,最多備份5個日誌
        try:
            rtfHandler = logging.BaseRotatingHandler(
                            filename, maxBytes=10*1024*1024, backupCount=5)
        except Exception as reason:
            self.error("%s" % reason)
        else:
            self.addHandler(rtfHandler)

def main():
    logfile1 = 'log/test1.log'
    logger1 = MyLogger(logfile1)
    logger1.debug("debug msg")
    logger1.info("info msg")
    logger1.warning("warning msg")
    logger1.error("error msg")
    logger1.critical("critical msg")

    logfile2 = 'log/test2.log'
    logger1 = MyLogger(logfile2)
    logger1.debug("debug msg")
    logger1.info("info msg")
    logger1.warning("warning msg")
    logger1.error("error msg")
    logger1.critical("critical msg")

if __name__ == '__main__':
    main()



本例封裝了類,在類中進行了統一的配置

終端輸出

2017-02-11 10:32:01,532 [mylogger.py:52][ERROR] error msg
2017-02-11 10:32:01,532 [mylogger.py:53][CRITICAL] critical msg
2017-02-11 10:32:01,533 [mylogger.py:60][ERROR] error msg
2017-02-11 10:32:01,533 [mylogger.py:61][CRITICAL] critical msg

log1檔案中記錄
2017-02-11 10:32:01,532 [mylogger.py:50][INFO] info msg
2017-02-11 10:32:01,532 [mylogger.py:51][WARNING] warning msg
2017-02-11 10:32:01,532 [mylogger.py:52][ERROR] error msg
2017-02-11 10:32:01,532 [mylogger.py:53][CRITICAL] critical msg