保存日志 - SimpleHTTPServer

2022-01-24 00:00:00 python logging save simplehttpserver

问题描述

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

How can I save the output from the console like

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

"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 打印所有日志消息.你有两个选择:

BaseHTTPRequestHandler.log_message() prints all log messages by writing to sys.stderr. You have two choices:

1) 继续使用BaseHTTPRequestHandler.log_message(),但是改变sys.stderr的值:

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) 新建一个xxxRequestHandler类,替换.log_message():

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

相关文章