前言
使用Python 装饰器decorator来对函数进行日志输出
_ 2021年3月 测试可用
环境
Python 3.7
代码
代码目录:
logger.py -> 日志装饰器: 用来写log日志的装饰器,以及log的基本设置
test.py -> 测试函数:调用logger里面写好的装饰器来进行测试
test-function.log -> log日志:输出错误信息
运行:
python3 test.py
具体代码
logger.py
import logging
from logging.handlers import TimedRotatingFileHandler
import os
import inspect
import config
from functools import wraps
import traceback
def _getLogger():
'''init logger'''
logger = logging.getLogger('test-function')
# specifies the lowest-severity log message a logger will handle,
# where debug is the lowest built-in severity level and critical is the highest built-in severity.
# For example, if the severity level is INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL
# messages and will ignore DEBUG messages.
logger.setLevel(logging.ERROR)
# create file handler which logs messages
fh = RotatingFileHandler('test-function.log', maxBytes=1024*1024, backupCount=1)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(fh)
logger.setLevel(logging.INFO)
return logger
def decorator_log(func):
@wraps(func)
def log(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
_getLogger().error(f"\n{func.__qualname__} is error,here are details:\n{traceback.format_exc()}")
return log
test.py
from logger import decorator_log
class Study:
@staticmethod
@decorator_log
def a():
a = [1, 2, 3]
# print(a)
a[6] = 100 # this is the wrong code
Study.a()
test-function.log
2021-03-16 18:27:17,874 - test-fcuntion - ERROR -
Study.a is error,here are details:
Traceback (most recent call last):
File "/home/hyh/2020_HBMS/hbms-api/logger.py", line 33, in log
return func(*args, **kwargs)
File "/home/hyh/2020_HBMS/hbms-api/test.py", line 10, in a
a[6] = 100
IndexError: list assignment index out of range
其他
如有收获 欢迎点赞
如有作用 欢迎留言
如有问题 欢迎指出