为pythons日志记录模块创建自定义日志记录功能

时间:2019-10-24 15:36:57

标签: python inheritance logging python-logging

我已经尝试了一段时间,以弄清楚如何为python日志记录模块创建自定义函数。我的目标是使用诸如logging.debug(...)之类的常用功能通过多个渠道(例如Telegram或MQTT)发送日志消息以进行发布。所以我的想法是向普通的log方法添加额外的参数。例如logging.debug ("a log", telegram=True, mqtt=False)以及其他参数。我所发现的只是类logging.StreamingHandler的继承,然后使用方法emit,但这仅传递了参数记录。那么我该如何以有意义的方式解决我的问题呢?我是思维错误还是方法错误?

1 个答案:

答案 0 :(得分:0)

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

我的代码的一小段视图:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from session session1_ cross join session_persons persons2_, person person3_ whe' at line 1

现在,使用uloggingConfig()方法,我可以传递不同处理程序的所有设置(此刻仅用于电报,应遵循其他处理程序)。然后,uloggingConfig()方法接管配置并返回一个记录器,可以像往常一样使用该记录器创建日志消息。

一个简单的例子:

# 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)