How do you override the BaseHTTPRequestHandler log_message () method to enter the file, not the console (sys.stderr)?

I am creating a web service using BaseHTTPServer.HTTPServer

I would like to register the following files to enter the file, not the console. But I have not yet been able to find a way to do this.

10.23.23.19 - - [29/Nov/2013 08:39:06] "GET / HTTP/1.1" 200 - 10.23.23.19 - - [29/Nov/2013 08:39:06] "POST / HTTP/1.1" 200 - 10.24.20.14 - - [29/Nov/2013 08:39:27] "POST / HTTP/1.1" 200 - 10.24.20.14 - - [29/Nov/2013 08:39:31] "POST / HTTP/1.1" 200 - 

My code is as follows:

 from BaseHTTPServer import HTTPServer from pysimplesoap.server import SoapDispatcher, SOAPHandler . # The rest of the code . . httpd = HTTPServer(("", 8059),SOAPHandler) httpd.dispatcher = dispatcher httpd.serve_forever() 

I am using Python 2.6

+6
source share
2 answers

If you read the document or source code for BaseHTTPRequestHandler, you will find that all logs go through BaseHTTPRequestHandler.log_message() , which docstring explicitly indicates:

Record an arbitrary message.

This is used by all other logging functions. Override it if you have specific logging wishes.

So the solution, obviously, should leave only .send_response() (obviously, you want your response to be sent), and replace .log_message() with the call to the appropriate logger (cf http://docs.python.org/2 /library/logging.html ), which is a clean and flexible way to handle a Python log, or if you just want to quickly crack a file system file entry.

+5
source

I managed to find a solution.

I created a logger with FileHandler in the pysimplesoap/server.py . I created the registrar immediately after the necessary import.

 httpdkenlogger = logging.getLogger('httpd-ken') #setup file handler fh = logging.FileHandler('/opt/python/dev/interim/httpd-kenserver.3.log') fh.setLevel(logging.INFO) frmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(frmt) # Add this handler to the logger httpdkenlogger.addHandler(fh) 

Subsequently, in the definition of the SOAPHandler class SOAPHandler I decided to override the log_message function as follows:

 class SOAPHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): httpdkenlogger.info("%s - - [%s] %s\n" % (self.address_string(),self.log_date_time_string(),format%args)) 
+4
source

Source: https://habr.com/ru/post/959030/


All Articles