python 記錄器

 python 有個 logging 的 module ,不難,能夠滿足輸出訊息到終端上,也能再存個檔來觀察,雖然要做到醬子並不難,透過官網的說明大致上每次大概使用同樣的10幾行就可以完成引用。由於還沒有找到像 laravel 一樣的 debugger 工具,希望之後每次引用只要1行就行,好在…已經有人把物件(class)寫好,存好檔後之後每次要引用只要1行就行。

 工作環境:
    Windows 10
    Python 3
        logging
        sys

 

#!/usr/local/bin python3
# -*- coding: utf-8 -*-
'''
# 使用方法:  
# import THIS_FILE_NAME(不包括 .py 的部份)
# logger = log.dLogger(log_file=myLog, name=myTag)
# logger.debug("字串;通常是執行的結果") 
# 結果: 2021-12-27 21:15:03,965 - myLogTag - DEBUG - blablabla 
'''
import logging
import sys
from logging import Logger
from logging.handlers import TimedRotatingFileHandler


class dLogger(Logger):
    def __init__(
        self,
        log_file=None,
        log_format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        *args,
        **kwargs
    ):
        self.formatter = logging.Formatter(log_format)
        self.log_file = log_file

        Logger.__init__(self, *args, **kwargs)

        self.addHandler(self.get_console_handler())
        if log_file:
            self.addHandler(self.get_file_handler())

        # 很少會用到,關了
        self.propagate = False
    
    # 在終端機顯示
    def get_console_handler(self):
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(self.formatter)
        return console_handler

    # 存檔
    def get_file_handler(self):
        file_handler = TimedRotatingFileHandler(self.log_file, when="midnight")
        file_handler.setFormatter(self.formatter)
        return file_handler

 

或是直接

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M',
                    handlers=[logging.FileHandler('myLog.txt', 'w', 'utf-8'), ])
 
logging.debug(someFunction(param))

 

 

 收工!

留言

這個網誌中的熱門文章

使用 Excel 計算2個地點之間的直線距離

LINE 儲存的檔案傳到 email 不方便 很不方便 非常不方便 但是有解的筆記

Excel 巨集合併多個 Excel 檔案