Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save logs - SimpleHTTPServer

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()
like image 517
Samantha Avatar asked Aug 18 '14 10:08

Samantha


2 Answers

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()
like image 174
Robᵩ Avatar answered Oct 29 '22 04:10

Robᵩ


I have used BaseHTTPServer instead of SimpleHTTPServer.

There you go:

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 5451

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):
        self.send_response(200)
        #self.send_header('Content-type','text/html')
        self.end_headers()
        text_file = open("ip.txt", "a")
        text_file.write(str(self.client_address) + "\n")
        text_file.close()
        # Send the html message
        #self.wfile.write("Hello World !")

        return

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER

    #Wait forever for incoming htto requests
    server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()
like image 25
Samantha Avatar answered Oct 29 '22 03:10

Samantha