python-记log

 

 

 

import traceback
import os
from datetime import datetime


def wrtLog(funName):
    def func_in(*args, **kwargs):
        try:
            return funName(*args, **kwargs)  # 返回值
        except:
            print(traceback.format_exc())
            saveLog(traceback.format_exc())
    return func_in


def saveLog(errMsg):
    try:
        if(not os.path.exists("C:\\RecFile")):
            os.makedirs("C:\\RecFile")
        with open("C:\\RecFile\\errLog.txt", 'a', encoding='utf8', errors='ignore') as fa:
            fa.write("\n记录时间:%s" % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            fa.write("\n-----------------------------------------------------------------------------\n")
            fa.write(errMsg)
            fa.write("\n=============================================================================\n")
    except:
        print(traceback.format_exc())

 

 

 

 

调用示例,

@是函数修饰符,是将下面的函数作为参数传到@后面的函数。

 

from writeLog import wrtLog

        
@wrtLog
def  div(a,b):
    c=a/b
    return c


c=div(7,0)

 

posted @ 2020-03-09 15:28  JinweiChang  阅读(197)  评论(0编辑  收藏  举报