如何保存控制台的输出,如
"192.168.1.1 - - [18/Aug/2014 12:05:59] code 404, message File not found"
到一个文件?
代码如下:
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()
通过写入sys.stderr
打印所有日志消息。您有两个选择:
1)继续使用BaseHTTPRequestHandler.log_message()
,但改变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)创建一个新的xxxRequestHandler
类,替换.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] %sn" %
(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()
我使用的是BaseHTTPServer而不是SimpleHTTPServer。
给你:
#!/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()