【问题标题】:Python logging : Log data to server using the logging modulePython 日志记录:使用日志记录模块将数据记录到服务器
【发布时间】:2020-11-07 11:40:59
【问题描述】:

日志模块提供了使用 HTTPHandler 的可能性, 由于格式的限制,这不符合我的要求。

如文档中所述,https://docs.python.org/3/library/logging.handlers.html,使用 setFormatter() 为 HTTPHandler 指定 Formatter 无效。

我的目标是在我的应用程序中记录事件,并在本地服务器上收集它们。 我正在使用 JSON-Server 来模拟 REST API (https://github.com/typicode/json-server)。 我已参考此链接:How to set up HTTPHandler for python logging,作为可能的解决方案,但我无法获得所需的内容。

我的代码:

"""class CustomHandler(logging.handlers.HTTPHandler):
    def __init__(self):
        logging.handlers.HTTPHandler.__init__(self)

    def emit(self, record):
        log_entry = self.format(record)
        # some code....
        url = 'http://localhost:3000/posts'
        # some code....
        return requests.post(url, log_entry, json={"Content-type": "application/json"}).content """

def custom_logger(name):

    logger = logging.getLogger(name)

    formatter_json = jsonlogger.JsonFormatter(
        fmt='%(asctime)s %(levelname)s %(name)s %(message)s') 

    requests.post('http://localhost:3000/posts', json= {"message" : "1" } ) 

 
    filehandler_all = logging.FileHandler('test.log')
    filehandler_all.setLevel(logging.DEBUG)
    filehandler_all.setFormatter(formatter_json)           
    logger.addHandler(filehandler_all)


    #http_handler = logging.handlers.HTTPHandler('http://localhost:3000' ,
     #"/posts", "POST")
    #
    # http_handler = CustomHandler()
   # http_handler.setFormatter(formatter_json)  
   # http_handler.setLevel(logging.DEBUG)
   
    return logger

logger = custom_logger("http")
logger.exception("{'sample json message' : '2'}")

cmets 用于测试,便于代码的重现。

在上面的代码sn-p中,filehandler完美的处理了json文件,但是HTTPHandler却没有。我尝试按照链接中的说明创建一个 CustomHandler,它原则上应该可以工作,但我无法弄清楚细节。

构造一个改变“mapLogRecord”和“emit”方法的CustomHandler有意义吗?

最重要的是获取JSON格式的数据。

解决此问题的任何其他想法也会有所帮助!

【问题讨论】:

  • mapLogRecord 的更改是有意义的。对emit 的更改没有意义。根本问题是记录的不是字符串,而是LogRecord 对象,这些对象需要以某种方式转换为字符串。
  • 谢谢,朝着正确的方向前进是有意义的。另一件事,可能是直接使用 HTTP 处理程序,并过滤掉服务器上的日志消息。这是我的最后一种方法,当我找到解决方案时会更新这个问题。

标签: python python-3.x logging python-requests python-logging


【解决方案1】:

好的,这是一个可以在服务器上输出 JSON 格式日志的解决方案。它使用自定义记录器。我还能够格式化消息以使其适用。下面的代码给出了 json 格式的输出,并使用了 request 模块。

class RequestsHandler(logging.Handler):
    def emit(self, record):
        log_entry = self.format(record)
        return requests.post('http://localhost:3000/posts',
                             log_entry, headers={"Content-type": "application/json"}).content

class FormatterLogger(logging.Formatter):
    def __init__(self, task_name=None):
        
        super(FormatterLogger, self).__init__()

    def format(self, record):
        data = {'@message': record.msg,                
                 '@funcName' : record.funcName,
                 '@lineno' : record.lineno,
                 '@exc_info' : record.exc_info, 
                 '@exc_text' : record.exc_text,                 
                 }           

        return json.dumps(data)



def custom_logger(name):
    logger = logging.getLogger(name)
    custom_handler = RequestsHandler()
    formatter = FormatterLogger(logger)
    custom_handler.setFormatter(formatter)
    logger.addHandler(custom_handler)
    
    return logger


logger = custom_logger("http")
logger.exception("{'sample json message' : '2'}")

数据变量控制可以添加到消息中的参数。

输出:

 {
      "@message": "{'sample json message' : '2'}",
      "@funcName": "<module>",
      "@lineno": 62,
      "@exc_info": [
        null,
        null,
        null
      ],
      "@exc_text": null,
      "id": 138
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2011-11-29
    相关资源
    最近更新 更多