保存日志 - SimpleHTTPServer

时间:2014-08-18 10:07:47

标签: python logging save simplehttpserver

如何保存控制台的输出,如

" 192.168.1.1 - - [18 / Aug / 2014 12:05:59]代码404,消息文件未找到"

到文件?

以下是代码:

import SimpleHTTPServer
import SocketServer

PORT = 1548

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

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

print "serving at port", PORT

httpd.serve_forever()

2 个答案:

答案 0 :(得分:14)

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] %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()

答案 1 :(得分:0)

我使用的是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()