Python3 装饰器进行log日志输出

前言

使用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

其他

如有收获 欢迎点赞
如有作用 欢迎留言
如有问题 欢迎指出

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hyh123a

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值