自定义日志处理程序无法在uWSGI下运行

问题描述

我已经编写了一个基于小型JSON-RPC库的Python-Wsgi应用程序。它使用定制的日志处理程序(请参见下文)将日志信息发送到MQTT-broker。到目前为止,我是通过wsgiref.simple_server(测试)或Apache mod_wsgi(生产版)启动应用程序的。 现在我切换到uWsgi,除了日志记录之外,其他一切都很好。

记录器处理程序:

import logging
import time
from typing import Union,Iterable
import paho.mqtt.client as mqtt
import datetime as DT
import json
import atexit


class MqttLogHandler(logging.Handler):
    """
    Logging handler that writes logs to MQTT broker
    """
    include = {'created','name','levelno','levelname','process','thread','filename','lineno','funcName'}

    def __init__(self,logname: str,broker: str,basetopic: str,include: Union[str,Iterable[str]] = None,exclude: Union[str,drain=0.2):
        self.logname = logname
        self.broker = broker
        self.topic = basetopic
        include = {include} if isinstance(include,str) \
            else set(include) if include else set()
        exclude = {exclude} if isinstance(exclude,str) \
            else set(exclude) if exclude else set()
        self.fields = self.include - exclude | include
        logging.Handler.__init__(self)
        self.mqttclient = mqtt.Client()
        self.mqttclient.connect(broker)
        atexit.register(lambda: time.sleep(drain))           # time to drain message queue
        self.mqttclient.loop_start()

    def emit(self,record: logging.LogRecord):
        info = {f.lower(): record.__dict__[f] for f in self.fields}
        info['message'] = self.format(record)
        info['logname'] = self.logname
        if 'created' in info:
            info['created'] = DT.datetime.fromtimestamp(record.created).isoformat(' ')
        topic = '/'.join((self.topic,self.logname,record.levelname))
        self.mqttclient.publish(topic,json.dumps(info))


class MqttLogFormatter(logging.Formatter):
    def init(self,style: str = '%'):
        super().__init__('%(message)s',None,style)

应用程序内部的设置:

    logger = logging.getLogger()
    logger.handlers = []

    handler = MqttLogHandler('MyLog','MyMqttbroker','logging')
    handler.setFormatter(MqttLogFormatter())
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)

如何告诉uWsgi不要触摸我的日志记录?

或者是否存在另一个具有生产能力的Web服务器应用程序,该应用程序对numpy没有问题;像apache和mod_wsgi一样?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)