python错误日志(logging)

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: ''
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值