SimpleHTTPServer的日志保存
你有两个选择:
1.通过写入BaseHTTPRequestHandler.log_message()
from http.server import HTTPServer, BaseHTTPRequestHandler
PORT_NUMBER = 5451
class myHandler(BaseHTTPRequestHandler):
buffer = 1
log_file = open('logfile.txt', 'w', buffer)
#将创建日志写入log_message()
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))
#GET请求的处理程序
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()
# 发送 html 信息
#self.wfile.write("Hello World !")
return
try:
#创建Web服务器并定义管理器
server = HTTPServer(('', PORT_NUMBER), myHandler)
print('Started httpserver on port ' , PORT_NUMBER)
#永远等待传入的http请求
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the web server')
server.socket.close()
2.打印所有日志消息sys.stderr
from http.server import HTTPServer, BaseHTTPRequestHandler
import sys
PORT_NUMBER = 5451
class myHandler(BaseHTTPRequestHandler):
#GET请求的处理程序
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()
# 发送 html 信息
#self.wfile.write("Hello World !")
return
try:
#创建Web服务器并定义管理器
server = HTTPServer(('', PORT_NUMBER), myHandler)
print('Started httpserver on port ' , PORT_NUMBER)
#写入打印所有日志消息
buffer = 1
sys.stderr = open('logfile.txt', 'w', buffer)
#永远等待传入的http请求
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the web server')
server.socket.close()