python 中logging的日志封裝


因為最近在做平台,發現有同事,使用django封裝了日志模塊,看樣子很簡單,准備自己單獨做了一個日志封裝模板,對於python不熟練的我,封裝部分參考了多個博主的內容,形成自己的日志模塊,內容如下:

封裝部分

創建一個logutil2的py文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: zhangjun
# @Date  : 2018/7/26 9:20
# @Desc  : Description

import logging
import logging.handlers
import os
import time

class logs(object):
    def __init__(self):
        self.logger = logging.getLogger("")
        # 設置輸出的等級
        LEVELS = {'NOSET': logging.NOTSET,
                  'DEBUG': logging.DEBUG,
                  'INFO': logging.INFO,
                  'WARNING': logging.WARNING,
                  'ERROR': logging.ERROR,
                  'CRITICAL': logging.CRITICAL}
        # 創建文件目錄
        logs_dir="logs2"
        if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
            pass
        else:
            os.mkdir(logs_dir)
        # 修改log保存位置
        timestamp=time.strftime("%Y-%m-%d",time.localtime())
        logfilename='%s.txt' % timestamp
        logfilepath=os.path.join(logs_dir,logfilename)
        rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =logfilepath,
                                                                   maxBytes = 1024 * 1024 * 50,
                                                                   backupCount = 5)
        # 設置輸出格式
        formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
        rotatingFileHandler.setFormatter(formatter)
        # 控制台句柄
        console = logging.StreamHandler()
        console.setLevel(logging.NOTSET)
        console.setFormatter(formatter)
        # 添加內容到日志句柄中
        self.logger.addHandler(rotatingFileHandler)
        self.logger.addHandler(console)
        self.logger.setLevel(logging.NOTSET)

    def info(self, message):
        self.logger.info(message)

    def debug(self, message):
        self.logger.debug(message)

    def warning(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)

  2.調用模塊

創建另外一個py文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: zhangjun
# @Date  : 2018/7/26 9:21
# @Desc  : Description
import logging
logger = logging.getLogger(__name__)
import logutil2

if __name__ == '__main__':
    logger=logutil2.logs()
    logger.info("this is info")
    logger.debug("this is debug")
    logger.error("this is error")
    logger.warning("this is warning")

  結果展示:

1.控制台輸出

2.日志文件展示

創建目錄

日志文件的寫入

 


免責聲明!

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



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