如何记录本地多线程 HTTP 服务器 python 的输出

Posted

技术标签:

【中文标题】如何记录本地多线程 HTTP 服务器 python 的输出【英文标题】:How to Log output of Local Multithread HTTP Server python 【发布时间】:2021-10-05 16:23:44 【问题描述】:

我有简单的 http python 多线程服务器

#http_server_threads.py

from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
import threading


class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type',
                         'text/plain; charset=utf-8')
        self.end_headers()
        message = threading.currentThread().getName()
        self.wfile.write(message.encode('utf-8'))
        self.wfile.write(b'\n')


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""


if __name__ == '__main__':
    server = ThreadedHTTPServer(('localhost', 8080), Handler)
    print('Starting server, use <Ctrl-C> to stop')
    server.serve_forever()

如果我卷曲

(base) padmanabanpr@padmanaban ~ % curl localhost:8080                   
Thread-1
(base) padmanabanpr@padmanaban ~ % curl localhost:8080
Thread-2
(base) padmanabanpr@padmanaban ~ % curl localhost:8080
Thread-3

在运行这个 python 代码时我得到了

% python3 http_server_threads.py 
Starting server, use <Ctrl-C> to stop
127.0.0.1 - - [30/Jul/2021 10:13:54] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [30/Jul/2021 10:13:59] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [30/Jul/2021 10:14:01] "GET / HTTP/1.1" 200 -

我需要将此输出记录到文件而不是显示, 需要记录的输出:(ip - - datetime "request type" response code - )

【问题讨论】:

那么通过简单地将其重定向到一个文件(即python3 http_server_threads.py 2&gt; file)有什么问题?另请参阅log_message: "...这通常被覆盖以创建自定义错误日志记录机制..." @SteffenUllrich 感谢您提供 log_message 信息。重定向的问题是我应该每 5 分钟获取一次此日志 【参考方案1】:

您可以使用此代码记录消息

from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
import threading


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type',
                         'text/plain; charset=utf-8')
        self.end_headers()
        message = threading.currentThread().getName()
        self.wfile.write(message.encode('utf-8'))
        self.wfile.write(b'\n')
        with open('server.log','a') as log_file:
            log_file.write(str(self.client_address)+' '+self.log_date_time_string()+' '+self.request_version+'\n')

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""


if __name__ == '__main__':
    server = ThreadedHTTPServer(('localhost', 8080), Handler)
    print('Starting server, use <Ctrl-C> to stop')
    server.serve_forever()

消息的输出如下:

python https_server_threads.py
Starting server, use <Ctrl-C> to stop
127.0.0.1 - - [15/Aug/2021 12:12:33] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [15/Aug/2021 12:12:33] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [15/Aug/2021 12:12:34] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [15/Aug/2021 12:12:34] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [15/Aug/2021 12:12:36] "GET / HTTP/1.1" 200 -

如果你检查文件 server.log 你会得到

('127.0.0.1', 60328) 15/Aug/2021 12:12:33 HTTP/1.1
('127.0.0.1', 60330) 15/Aug/2021 12:12:33 HTTP/1.1
('127.0.0.1', 60332) 15/Aug/2021 12:12:34 HTTP/1.1
('127.0.0.1', 60334) 15/Aug/2021 12:12:34 HTTP/1.1
('127.0.0.1', 60336) 15/Aug/2021 12:12:36 HTTP/1.1

【讨论】:

以上是关于如何记录本地多线程 HTTP 服务器 python 的输出的主要内容,如果未能解决你的问题,请参考以下文章

Python实现多线程HTTP下载器

Python多线程HTTP服务器不起作用

python 多线程将数据写入 influxDB

python 多线程将数据写入 influxDB

Python - 在多线程中使用随机数

python多线程学习记录