00九、日誌模塊(二) 、logging 二次封裝 , 單列模式

 

1、logging 二次封裝  ( 自定義 MyLogger 類  ) 

一、自定義MyLogger類:  

  a、目錄層級 :python

       

 

  b、my_logger.py  代碼以下:設計模式

   在模塊中, 生成一個 mylogger 實例,在其餘全部模塊中導入該模塊時,共用這一個日誌蒐集實例 (相似於全局變量)。日誌蒐集是典型的  單列設計模式  (單實例設計模式) 。 ide

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
# -*- coding:utf-8 -*-
# Author:  Sky
# Email:   2780619724@qq.com
# Time:    2021/8/3 11:13
# Module:  my_logger.py


# 自定義一個日誌模塊
import logging
from logging import Logger


class MyLogger(Logger):

    def __init__(self, logger_name, level='INFO', is_stream_handler=True, file=None):
        """
        實例化一個自定義日誌蒐集器
        :param logger_name: 日誌蒐集器的名字
        :param level: 日誌級別,默認是INFO級別
        :param is_stream_handler: 是否輸出到控制檯,默認輸出到控制檯
        :param file: 文件目錄,默認不輸出到 file
        """
        # 一、設置自定義日誌蒐集器名字、設置日誌級別;
        super().__init__(logger_name, level)

        # 二、定義日誌輸出格式, 使用Formatter類實例化一個日誌格式類;
        fmt = '%(asctime)s, %(levelname)s %(pathname)s,line=%(lineno)d, %(message)s, %(name)s'
        formatter = logging.Formatter(fmt)

        # 三、日誌默認輸出到控制檯,若是設置爲False,日誌將不輸出到控制檯;
        if is_stream_handler:
            stream_handler = logging.StreamHandler()
            # 設置渠道當中的日誌格式
            stream_handler.setFormatter(formatter)
            # 將渠道與實例日誌蒐集器綁定
            self.addHandler(stream_handler)

        # 四、把日誌輸出到文件file
        if file:
            file_handle = logging.FileHandler(file, mode='a', encoding='utf-8')
            # 設置渠道當中的日誌格式
            file_handle.setFormatter(formatter)
            # 將渠道與實例日誌蒐集器綁定
            self.addHandler(file_handle)


# 生成一個 mylogger 實例,在其餘全部模塊中導入該模塊時,共用這一個日誌蒐集實例。mylogger 相似於 全局變量
# 日誌蒐集是典型的單列設計模式 (單實例模式) 。
mylogger = MyLogger('日誌蒐集Demo', file='demo_log.txt')
View Code

 

  測試代碼:測試

  c、test_logger_cat.py 代碼以下:spa

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
# 導入 my_logger 模塊中 mylogger 實例;
from my_logger import mylogger


class Cat():

    def __init__(self, name):
        self.name = name

    def func(self):
        print('個人名字是: {0}'.format(self.name))
        mylogger.debug('debug日誌111')
        mylogger.info('info日誌222')
        mylogger.error('error日誌333')

    # 把異常信息輸出到 logging 中 ;
    # Exception as e  再打印 ;
    def test_raise(self):
        try:
            if str(123) + 12:
                mylogger.info('成功')
        except Exception as e:
                mylogger.error('異常信息爲:{}'.format(e))


if __name__ == '__main__':
    c = Cat('加菲')
    c.func()
    c.test_raise()
View Code

  d、test_logger_dog.py 代碼以下:debug

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
# 導入 my_logger 模塊中 mylogger 實例;
from my_logger import mylogger


class Dog():

    def __init__(self, name):
        self.name = name

    def func(self):
        print('個人名字是: {0}'.format(self.name))
        mylogger.debug('debug日誌444')
        mylogger.info('info日誌555')
        mylogger.error('error日誌666')


if __name__ == '__main__':
    d = Dog('哈士奇')
    d.func()
View Code

  e、test_cat_dog.py  代碼以下: 設計

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
from test_logger_cat import Cat
from test_logger_dog import Dog

c = Cat('加菲')
c.func()

d = Dog('哈士奇')
d.func()
View Code

 

  測試結果:日誌

  執行結果以下,同時在控制檯輸出:code

  deno_log.txt 中打印以下: orm

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
2021-08-03 18:11:38,489, INFO D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_cat.py,line=13, info日誌222, 日誌蒐集Demo
2021-08-03 18:11:38,490, ERROR D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_cat.py,line=14, error日誌333, 日誌蒐集Demo
2021-08-03 18:11:38,490, INFO D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_dog.py,line=13, info日誌555, 日誌蒐集Demo
2021-08-03 18:11:38,490, ERROR D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_dog.py,line=14, error日誌666, 日誌蒐集Demo
View Code

  控制檯輸出以下:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_cat_dog.py
2021-08-03 18:11:38,489, INFO D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_cat.py,line=13, info日誌222, 日誌蒐集Demo
2021-08-03 18:11:38,490, ERROR D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_cat.py,line=14, error日誌333, 日誌蒐集Demo
2021-08-03 18:11:38,490, INFO D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_dog.py,line=13, info日誌555, 日誌蒐集Demo
2021-08-03 18:11:38,490, ERROR D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\study\test_logger_dog.py,line=14, error日誌666, 日誌蒐集Demo
個人名字是: 加菲
個人名字是: 哈士奇

Process finished with exit code 0
View Code

 

 

二、把異常信息輸出到 logging 中 ;

   my_logger.py  代碼以下 (延用上面封裝好的 MyLogger 類,代碼同樣): 

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
# -*- coding:utf-8 -*-
# Author:  Sky
# Email:   2780619724@qq.com
# Time:    2021/8/3 11:13
# Module:  my_logger.py


# 自定義一個日誌模塊
import logging
from logging import Logger


class MyLogger(Logger):

    def __init__(self, logger_name, level='INFO', is_stream_handler=True, file=None):
        """
        實例化一個自定義日誌蒐集器
        :param logger_name: 日誌蒐集器的名字
        :param level: 日誌級別,默認是INFO級別
        :param is_stream_handler: 是否輸出到控制檯,默認輸出到控制檯
        :param file: 文件目錄,默認不輸出到 file
        """
        # 一、設置自定義日誌蒐集器名字、設置日誌級別;
        super().__init__(logger_name, level)

        # 二、定義日誌輸出格式, 使用Formatter類實例化一個日誌格式類;
        fmt = '%(asctime)s, %(levelname)s %(pathname)s,line=%(lineno)d, %(message)s, %(name)s'
        formatter = logging.Formatter(fmt)

        # 三、日誌默認輸出到控制檯,若是設置爲False,日誌將不輸出到控制檯;
        if is_stream_handler:
            stream_handler = logging.StreamHandler()
            # 設置渠道當中的日誌格式
            stream_handler.setFormatter(formatter)
            # 將渠道與實例日誌蒐集器綁定
            self.addHandler(stream_handler)

        # 四、把日誌輸出到文件file
        if file:
            file_handle = logging.FileHandler(file, mode='a', encoding='utf-8')
            # 設置渠道當中的日誌格式
            file_handle.setFormatter(formatter)
            # 將渠道與實例日誌蒐集器綁定
            self.addHandler(file_handle)


# 生成一個 mylogger 實例,在其餘全部模塊中導入該模塊時,共用這一個日誌蒐集實例。mylogger 相似於 全局變量
# 日誌蒐集是典型的單列設計模式 (單實例模式) 。
mylogger = MyLogger('日誌蒐集Demo', file='demo_log.txt')
View Code

 

  測試代碼:

  test_logger_cat.py 代碼改動以下。主要改動(添加了一個異常測試代碼)

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
# 導入 my_logger 模塊中 mylogger 實例;
from my_logger import mylogger


class Cat():

    def __init__(self, name):
        self.name = name

    def func(self):
        print('個人名字是: {0}'.format(self.name))
        mylogger.debug('debug日誌111')
        mylogger.info('info日誌222')
        mylogger.error('error日誌333')

    # 把異常信息輸出到 logging 中 ;
    # Exception as e  再打印 ;
    def test_raise(self):
        try:
            if str(123) + 12:
                mylogger.info('成功')
        except Exception as e:
                mylogger.error('異常信息爲:{}'.format(e))


if __name__ == '__main__':
    c = Cat('加菲')
    c.func()
    c.test_raise()
View Code

 

  測試結果:

  在 test_logger_cat.py 中 run,能夠看到把 異常信息輸出到  logging中了;

  deno_log.txt 中打印以下:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
2021-08-03 18:20:39,728, INFO D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_logger_cat.py,line=13, info日誌222, 日誌蒐集Demo
2021-08-03 18:20:39,728, ERROR D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_logger_cat.py,line=14, error日誌333, 日誌蒐集Demo
2021-08-03 18:20:39,729, ERROR D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_logger_cat.py,line=23, 異常信息爲:can only concatenate str (not "int") to str, 日誌蒐集Demo
View Code

  控制檯輸出以下:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day10\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_logger_cat.py
個人名字是: 加菲
2021-08-03 18:20:39,728, INFO D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_logger_cat.py,line=13, info日誌222, 日誌蒐集Demo
2021-08-03 18:20:39,728, ERROR D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_logger_cat.py,line=14, error日誌333, 日誌蒐集Demo
2021-08-03 18:20:39,729, ERROR D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day10/study/test_logger_cat.py,line=23, 異常信息爲:can only concatenate str (not "int") to str, 日誌蒐集Demo

Process finished with exit code 0
View Code
相關文章
相關標籤/搜索