Guardar registros – SimpleHTTPServer

¿Cómo puedo guardar la salida de la consola como

“192.168.1.1 – – [18 / Ago / 2014 12:05:59] código 404, mensaje Archivo no encontrado”

a un archivo?

Aquí está el código:

import SimpleHTTPServer import SocketServer PORT = 1548 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever() 

BaseHTTPRequestHandler.log_message() imprime todos los mensajes de registro escribiendo a sys.stderr . Tienes dos opciones:

1) Continúe usando BaseHTTPRequestHandler.log_message() , pero cambie el valor de 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) Crea una nueva clase xxxRequestHandler , reemplazando .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() 

He usado BaseHTTPServer en lugar de SimpleHTTPServer.

Hay que ir

 #!/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()