繁体   English   中英

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

[英]Python logging : Log data to server using the logging module

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

如文档中所述, https://docs.python.org/3/library/logging.handlers.html 对 HTTP使用 setFormatter() 没有指定 aHandler 的效果。

我的目标是在我的应用程序中记录事件,并在本地服务器上收集它们。 我正在使用 JSON-Server 来模拟 REST API ( https://github.com/typicode/json-server )。 我已经参考了这个链接: 如何为 python 日志设置 HTTPHandler ,作为一种可能的解决方案,但我无法获得所需的内容。

我的代码:

"""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'}")

注释用于测试,便于代码的复制。

在上面的代码片段中,文件处理程序完美地处理了 json 文件,但 HTTPHandler 没有。 我尝试按照链接中的指定创建一个 CustomHandler 原则上应该可以工作,但我无法弄清楚细节。

构造一个对“mapLogRecord”和“emit”方法进行更改的 CustomHandler 是否有意义?

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

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

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

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'}")

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

output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM