日志模块提供了使用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格式获取数据
任何其他的方法也会有帮助
好的,这是一个可以在服务器上以JSON格式输出日志的解决方案。它使用自定义记录器。我也能够格式化信息的适用性。下面的代码以json格式提供输出,并使用请求模块
数据变量控制可添加到消息中的参数
输出:
相关问题 更多 >
编程相关推荐