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

2024-05-08 00:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我的目标是在应用程序中记录事件,并在本地服务器上收集它们。 我正在使用JSON服务器模拟RESTAPI(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格式获取数据

任何其他的方法也会有帮助


Tags: 代码selflogjsonhttplogginghandlersdef
1条回答
网友
1楼 · 发布于 2024-05-08 00:14:17

好的,这是一个可以在服务器上以JSON格式输出日志的解决方案。它使用自定义记录器。我也能够格式化信息的适用性。下面的代码以json格式提供输出,并使用请求模块

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
    }

相关问题 更多 >