为 pythons 日志记录模块创建自定义日志记录函数

Create custom logging function for pythons logging module

一段时间以来,我一直在尝试弄清楚如何为 python 日志记录模块创建自定义函数。我的目标是,通过 logging.debug(...) 等常用功能,通过多个渠道(如 Telegram 或 MQTT)发布日志消息。所以我的想法是向普通日志方法添加额外的参数。例如 logging.debug ("a log", telegram=True, mqtt=False) 和其他参数。我找到的只是classlogging.StreamingHandler的继承,然后使用方法emit,但这只是传递了参数记录。那么我怎样才能以有意义的方式解决我的问题呢?是我思路错误还是方法不对?

我通过为日志记录模块创建接口解决了我的问题。

对我的代码的一点看法:

# ulogging.py
import logging
import telegram

def uloggingConfig(*args, **kwargs):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    # general logging config section
    fmt = kwargs.pop("fmt", "%(asctime)s %(levelname)s %(message)s")
    datefmt = kwargs.pop("datefmt", "%m.%d.%Y %I:%M:%S %p")

    streamHandler = logging.StreamHandler()
    streamHandler.setLevel(logging.DEBUG)
    formater = logging.Formatter(fmt=fmt, datefmt=datefmt)
    streamHandler.setFormatter(formater)
    logger.addHandler(streamHandler)

    # telegram config section
    telegramBot = kwargs.pop("teleBot", None)
    telegramChatID = kwargs.pop("teleChatID", None)
    telegramLevel = kwargs.pop("teleLevel", logging.INFO)
    telegramFmt = kwargs.pop("telefmt", "%(message)s")
    telegramDatefmt = kwargs.pop("teledatefmt", None)

    if telegramBot is not None and telegramChatID is not None:
        telegramStream = TelegramStream(telegramBot, telegramChatID)
        formater = logging.Formatter(fmt=telegramFmt, datefmt=telegramDatefmt)
        telegramStream.setFormatter(formater)
        telegramStream.setLevel(telegramLevel)
        logger.addHandler(telegramStream)
    elif (telegramBot is not None and telegramChatID is None) or (telegramBot is None and telegramChatID is not None):
        raise KeyError("teleBot and teleChatID have to be both given")

    if kwargs:
        keys = ', '.join(kwargs.keys())
        raise ValueError('Unrecognised argument(s): %s' % keys)

    return logger

def getLogger():
    return logging.getLogger(__name__)

class TelegramStream(logging.StreamHandler):
    def __init__(self, telegramBot, telegramChatID):
        logging.StreamHandler.__init__(self)
        self._bot = telegramBot
        self._chatID = telegramChatID

    def emit(self, record):
        if record.levelname == "DEBUG":
            self._bot.send_message(self._chatID, record.levelname + ": " + record.msg)
        else:
            self._bot.send_message(self._chatID, record.msg)

使用 uloggingConfig() 方法,我现在可以为不同的处理程序传递所有设置(目前仅针对电报,应该有更多的处理程序)。然后 uloggingConfig() 方法接管配置和 returns 一个可以像往常一样创建日志消息的记录器。

一个简单的例子:

logger = ulogging.uloggingConfig(fmt="format, datefmt="dateformat, teleBot=telegramBot, teleChatID=telegramChatID, teleLevel=logging.DEBUG)

logger.debug("A log message")