gpt4 book ai didi

python - 如何在 python 记录器中记录请求特定属性

转载 作者:行者123 更新时间:2023-11-28 20:30:25 24 4
gpt4 key购买 nike

我有一个 python 文件 'server.py'

#!/usr/bin/env python

import sys, BaseHTTPServer
from mylogger import logging
logger = logging.getLogger(__name__)

class RESTRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
logger.error('Just random log')
self.send_response(200)
self.end_headers()

def rest_server(port):
'Starts the REST server'
http_server = BaseHTTPServer.HTTPServer(('', port), RESTRequestHandler)
print 'Starting HTTP server at port %d' % port
try:
http_server.serve_forever()
except KeyboardInterrupt:
pass
print 'Stopping HTTP server'
http_server.server_close()

def main(argv):
rest_server(8080)

if __name__ == '__main__':
main(sys.argv[1:])

我有另一个文件 'mylogger.py'

__all__ = ['logging']

import logging
FORMAT = '%(asctime)s | %(tid)d | %(message)s'

def req_extractor(*args, **kargs):
print(args)
print(kargs)
print(locals())
# here i want to get request X-App-Tid
return {'tid': 1}

class CustomLogger(logging.Logger):
def _log(self, level, msg, args, exc_info=None, extra=None):
reqObj = req_extractor()
if extra is None: extra = {}
reqObj.update(extra)
super(CustomLogger, self)._log(level, msg, args, exc_info, reqObj)

logging.setLoggerClass(CustomLogger)

logging.basicConfig(
filename='python.log',
format=FORMAT,
datefmt='%m/%d/%Y %I:%M:%S %p',
level=logging.DEBUG)

当我进行 curl 调用时

curl -H 'X-App-Tid:1' -i http://localhost:8080

我明白了

07/23/2019 04:50:45 PM | 1 | Just random log

我可以在日志中打印 tid,但我想从请求 header X-App-Tid 中提取它

注意:文件 server.py 不允许更改,但我可以在 mylogger.py 中进行任何更改

有什么帮助吗?

最佳答案

你可以像下面这样更新你的记录器来覆盖现有的类

__all__ = ['logging']

import logging

import BaseHTTPServer
org = BaseHTTPServer.BaseHTTPRequestHandler

current_class = None

class MyClass(BaseHTTPServer.BaseHTTPRequestHandler, object):

def parse_request(self):
global current_class
current_class = self
value = super(MyClass, self).parse_request()

return value

BaseHTTPServer.BaseHTTPRequestHandler = MyClass

FORMAT = '%(asctime)s | %(tid)d | %(message)s'

def req_extractor(*args, **kargs):
print(args)
print(kargs)
print(locals())
global current_class
if current_class:
print current_class.headers['X-App-Tid']
# here i want to get request
return {'tid': 1}

class CustomLogger(logging.Logger):
def _log(self, level, msg, args, exc_info=None, extra=None):
reqObj = req_extractor()
if extra is None: extra = {}
reqObj.update(extra)
super(CustomLogger, self)._log(level, msg, args, exc_info, reqObj)

logging.setLoggerClass(CustomLogger)

logging.basicConfig(
filename='python.log',
format=FORMAT,
datefmt='%m/%d/%Y %I:%M:%S %p',
level=logging.DEBUG)

然后就可以了

Header printed

关于python - 如何在 python 记录器中记录请求特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57163200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com