1. 程式人生 > 其它 >python錯誤日誌(logging)

python錯誤日誌(logging)

技術標籤:pythonpython

python錯誤日誌

檔案內寫法
獲取錯誤檔名、函式名、行數、錯誤詳情

try'''code'''
except Exception as e:
        filename = sys._getframe().f_code.co_filename
        function = sys._getframe().f_code.co_name
        lineno = sys._getframe().f_lineno
        exception = str(e)
        log.printing(filename,
function, lineno, exception) return

log.py

import os
import sys
import time
import logging


def printing(filename, function, lineno, e):
    current_path = os.path.abspath(__file__)
    parent_path = os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".")
    today = time.
strftime('%Y-%m-%d', time.localtime(time.time())) logName = today + "_e.log" if not os.path.exists("{}/logDir/toolLog/".format(parent_path)): os.makedirs("{}/logDir/toolLog/".format(parent_path)) if not os.path.exists("{}/logDir/toolLog/{}/".format(parent_path,
today)): os.makedirs("{}/logDir/toolLog/{}/".format(parent_path, today)) if not os.path.exists("{}/logDir/toolLog/{}/{}".format(parent_path, today, logName)): reportFile = open("{}/logDir/toolLog/{}/{}".format(parent_path, today, logName), 'w') reportFile.close() logger = logging.getLogger() handler = logging.FileHandler("{}/logDir/toolLog/{}/{}".format(parent_path, today, logName), encoding='utf8') console = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(filename)s %(funcName)s %(levelname)s %(message)s') print(str(formatter)) handler.setFormatter(formatter) # 將log資訊繫結到log檔案上 console.setFormatter(formatter) # 將log資訊繫結到控制檯輸出視窗 logger.addHandler(handler) logger.addHandler(console) logger.setLevel(logging.INFO) # Set log print level(設定日誌列印級別) logging.info(filename + ' Function: ' + function + ' Line: ' + str(lineno) + ' Exception: ' + e) # print(e,'log.py')

輸出結果:
在這裡插入圖片描述

2020-12-30 11:51:51,890 log.py printing INFO C:/Users/hp/PycharmProjects/screw_system/display/main.py   Function:refresh  Line:502   Exception: [Errno 2] No such file or directory: ''