记录来自 docker 容器的所有 HTTP 请求的响应时间

问题描述 投票:0回答:1

我构建了一个 docker 映像,其中包含一个无法添加日志记录语句的预构建应用程序。应用程序在执行时发出许多 HTTP 请求,我想记录这些请求,特别是完成这些响应所需的时间。我是否可以向我的 docker 容器添加一些东西(例如代理),让我可以记录所有 HTTP 请求的响应时间?

python docker httprequest http-proxy
1个回答
0
投票

您可以通过在应用程序前面放置一个能够记录响应时间的反向代理来获取有关应用程序响应时间的数据。我在回答中使用了 Nginx。

为了创建一个要测量的应用程序,我使用了这个 Dockerfile,它创建了一个 C# Web API 应用程序,该应用程序侦听端口 80 并响应

/weatherforecast
上的请求。

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
RUN dotnet new webapi -n myapp -o . --no-https
RUN dotnet publish -o /app

FROM mcr.microsoft.com/dotnet/aspnet:7.0
WORKDIR /app
COPY --from=build /app /app
CMD ["dotnet", "myapp.dll"]

我们将使用此 docker-compose.yml 文件来编排应用程序和 Nginx

version: '3'

services:
  myapp:
    build: .
  nginx:
    image: nginx:latest
    ports:
      - 8000:80
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf

这将运行应用程序(“myapp”)和 Nginx。 Nginx 监听主机端口 8000 并配置了一个名为 nginx.conf 的文件,如下所示:

log_format upstream_time '$remote_addr - $remote_user [$time_local] '
                             '"$request" $status $body_bytes_sent '
                             '"$http_referer" "$http_user_agent" '
                             '"$upstream_response_time"';
server {
  listen 80;
  location / {
    proxy_pass http://myapp/;
  }
  access_log /var/log/nginx/access.log upstream_time;
}

在此文件中,我们为 Nginx 指定了自定义日志格式,其中包括

$upstream_response_time
作为日志条目的最后部分。 Nginx 还配置为将所有请求传递到
myapp
应用程序。

运行它,发出几个请求并使用

查看 Nginx 日志
docker compose up -d
curl http://localhost:8000/weatherforecast
curl http://localhost:8000/weatherforecast
docker compose logs nginx

我的输出如下所示,两个请求的响应时间记录为 68 毫秒和 3 毫秒(响应时间位于日志条目的末尾)

nginx_1  | 172.22.0.1 - - [07/Oct/2023:09:51:16 +0000] "GET /weatherforecast HTTP/1.1" 200 394 "-" "curl/7.81.0" "0.068"
nginx_1  | 172.22.0.1 - - [07/Oct/2023:09:52:13 +0000] "GET /weatherforecast HTTP/1.1" 200 393 "-" "curl/7.81.0" "0.003"
© www.soinside.com 2019 - 2024. All rights reserved.