Python日志记录:使用日志记录模块将数据记录到服务器

时间:2020-07-17 16:08:21

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

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

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

我的目的是在我的应用程序中记录事件,并将事件收集在本地服务器上。 我正在使用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'}")

这些注释用于测试,并且易于复制代码。

在上面的代码片段中,filehandler可以完美地处理json文件,而HTTPHandler则不能。我尝试按照链接中的说明创建一个CustomHandler,该链接原则上应该可以工作,但是我无法弄清楚细节。

使用“ mapLogRecord”和“ emit”方法的更改来构造CustomHandler有意义吗?。

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

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

1 个答案:

答案 0 :(得分:0)

好的,所以这是一个可以在服务器上以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
    }