You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python http.server日志格式:添加服务名与ISO时间?

解决方法

要修改Python http.server的日志格式,你需要自定义请求处理器覆盖默认的日志生成逻辑,再让systemd服务调用这个自定义脚本,具体步骤如下:

1. 编写自定义HTTP服务器脚本

创建一个名为custom_http_server.py的文件,继承BaseHTTPRequestHandler并重写log_message方法,实现目标日志格式:

from http.server import HTTPServer, BaseHTTPRequestHandler
from datetime import datetime

class CustomHTTPRequestHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        # 生成ISO格式的日期时间
        iso_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 构造符合要求的日志条目
        log_line = f'{self.address_string()} - http.server - [{iso_time}] "{format % args}"'
        print(log_line)

if __name__ == '__main__':
    # 绑定端口,可根据需求修改为其他端口
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, CustomHTTPRequestHandler)
    httpd.serve_forever()

代码说明:

  • log_message是BaseHTTPRequestHandler中负责输出日志的核心方法,重写它就能完全自定义日志格式
  • strftime('%Y-%m-%d %H:%M:%S')直接生成你需要的ISO标准日期时间
  • 日志结构调整为IP地址 - 服务名 - [ISO时间] "请求详情" 状态码 -,完全匹配需求

2. 配置systemd服务文件

假设你的systemd服务文件路径为/etc/systemd/system/http-server.service,修改ExecStart指令指向自定义脚本,同时保留日志追加配置:

[Unit]
Description=Custom HTTP Server
After=network.target

[Service]
User=your-user
Group=your-group
ExecStart=/usr/bin/python3 /path/to/custom_http_server.py
Restart=always
# 配置日志追加到指定文件
StandardOutput=append:/var/log/http-server.log
StandardError=append:/var/log/http-server.log

[Install]
WantedBy=multi-user.target

配置说明:

  • 替换your-user、your-group为实际运行服务的用户/用户组
  • 替换/path/to/custom_http_server.py为脚本的实际存储路径
  • append:前缀确保日志以追加模式写入文件,不会覆盖原有内容

3. 重启systemd服务使配置生效

执行以下命令更新服务配置并重启:

sudo systemctl daemon-reload
sudo systemctl restart http-server.service

之后查看日志文件/var/log/http-server.log,就能看到符合要求的日志条目,示例:

192.168.1.100 - http.server - [2023-05-18 22:05:30] "GET /index.html HTTP/1.1" 304 -

内容的提问来源于stack exchange,提问作者Lonerider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:12:08