如何设置HTTPHandler进行python日志记录 [英] How to set up HTTPHandler for python logging

查看:250
本文介绍了如何设置HTTPHandler进行python日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用标准python日志记录库的HTTPHandler类发送日志.我需要使用基本凭据(用户名和密码)发出https发布请求.这就是我设置HTTPHandler-

I'm trying to use HTTPHandler class of standard python logging library to send logs. I need to make a https post request with basic credentials(username and password). This is how i'm setting up the HTTPHandler-

    host = 'example.com'
    url = '/path'
    handler = logging.handlers.HTTPHandler(host, url, method='POST', secure=True, credentials=('username','password'), context=None)
    logger.addHandler(handler)

但是问题是,我在远程服务器上没有收到任何日志,甚至没有从处理程序中看到任何异常.我是否错误地设置了处理程序参数?我可以使用简单的pythong http request-

But the problem is, I'm not getting anylogs in my remote server.I'm not even seeing any exception from the handler. Am I setting up the handler arguments incorrectly? I can send similar logs using simple pythong http request-

url = 'https://username:password@example.com/path'
headers = {'content-type': 'application/json'}
jsonLog = { 'id': '4444','level': 'info', 'message': 'python log' };

r = requests.post(url, data = json.dumps(jsonLog), headers=headers)

由于json内容类型,我是否需要以某种方式设置标头?如果可以,我该如何在httphandler中进行设置?

Do i need to setup header somehow because of json content-type? If yes than how do i set that up in the httphandler?

更新

我认为我应该更新自己最终做的事情.经过大量搜索之后,我发现我可以通过覆盖logging.Handler的emit()创建一个自定义处理程序.

I thought I should update what I ended up doing. After numerous search i found i can create a custom handler by overriding emit() of logging.Handler.

class CustomHandler(logging.Handler):
def emit(self, record):
    log_entry = self.format(record)
    # some code....
    url = 'url'
    # some code....
    return requests.post(url, log_entry, headers={"Content-type": "application/json"}).content

如果有任何更好的建议,请随时发表.

Feel free to post if any has any better suggestions.

推荐答案

您将需要继承HTTPHandler的子类,并覆盖emit()方法以执行所需的操作.您可以使用HTTPHandler.emit()的当前实现作为指导.

You will need to subclass HTTPHandler and override the emit() method to do what you need. You can use the current implementation of HTTPHandler.emit() as a guide.

这篇关于如何设置HTTPHandler进行python日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆