gpt4 book ai didi

python - 保存日志 - SimpleHTTPServer

转载 作者:太空狗 更新时间:2023-10-29 21:24:13 25 4
gpt4 key购买 nike

如何保存控制台的输出

“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()

最佳答案

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

关于python - 保存日志 - SimpleHTTPServer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25360798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com