Save logs - SimpleHTTPServer(保存日志 - 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()
这篇关于保存日志 - SimpleHTTPServer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:保存日志 - SimpleHTTPServer


基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01