Python的日志类

# log_module.py
import logging
import inspect
import os


class StandardLogger:
    def __init__(self, log_file='my_log.log'):
        # log_file根据项目实际情况设置,建议配置文件获取
        self.logger = logging.getLogger("product")
        self.logger.setLevel(logging.DEBUG)

        formatter = logging.Formatter('【%(asctime)s】【%(levelname)s】【%(name)s】【%(message)s】')
        # 写入日志文件
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)

        # 写入控制台(可选)
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)

    def log(self, level, message):
        frame = inspect.stack()[1]
        module = inspect.getmodule(frame[0])
        file_path = os.path.abspath(module.__file__)
        function_name = frame[3]
        line_number = frame[2]

        log_message = f"File: {file_path}, Function: {function_name}, Line: {line_number} {message} "
        getattr(self.logger, level)(log_message)


syslog = StandardLogger()

可在其他模块调用

# test_log.py
from log_module import syslog


def info():
    syslog.log("info", "This is an info message.")


def warn():
    syslog.log("warning", "This is a warning message.")


def error():
    syslog.log("error", "This is an error message.")


if __name__ == "__main__":
    info()
    warn()
    error()

调用结果

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值