Save logs - SimpleHTTPServer

Samantha picture Samantha · Aug 18, 2014 · Viewed 18.8k times · Source

How can I save the output from the console like

"192.168.1.1 - - [18/Aug/2014 12:05:59] code 404, message File not found"

to a file?

Here is the code:

import SimpleHTTPServer
import SocketServer

PORT = 1548

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT

httpd.serve_forever()

Answer

Robᵩ picture Robᵩ · Aug 19, 2014

BaseHTTPRequestHandler.log_message() prints all log messages by writing to sys.stderr. You have two choices:

1) Continue using BaseHTTPRequestHandler.log_message(), but change the value of sys.stderr:

import SimpleHTTPServer
import SocketServer

PORT = 1548

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT

import sys
buffer = 1
sys.stderr = open('logfile.txt', 'w', buffer)
httpd.serve_forever()

2) Create a new xxxRequestHandler class, replacing .log_message():

import SimpleHTTPServer
import SocketServer
import sys

PORT = 1548

class MyHTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    buffer = 1
    log_file = open('logfile.txt', 'w', buffer)
    def log_message(self, format, *args):
        self.log_file.write("%s - - [%s] %s\n" %
                            (self.client_address[0],
                             self.log_date_time_string(),
                             format%args))

Handler = MyHTTPHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT

httpd.serve_forever()