【问题标题】:How to log http request body from nginx docker image?如何从 nginx docker 映像记录 http 请求正文?
【发布时间】:2018-09-16 09:32:19
【问题描述】:

我有一个带有 nginx 的 docker 映像。

我想记录传入的请求。

我的 docker-compose 文件:

nginx:
  container_name: my-nginx
image: nginx
ports:
  - "80:80"
  - "443:443"
volumes:
  - ./nginx.conf:/etc/nginx/conf.d/default.conf
  - ./access.log:/var/log/nginx/test.com.access.log

我的 nginx 配置:

server {
 listen 80;
 listen 443 default_server ssl;
 access_log /var/log/nginx/test.com.access.log;

 location / {
  proxy_pass http://myapp:8080;
  proxy_buffering off;
 }
}

当我尝试用以下配置替换 access_log 指令时:

log_format testlog '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $bytes_sent '
                   '"$http_referer" "$http_user_agent" "$request_body"';
access_log /var/log/nginx/test.com.access.log testlog;

我明白了:

nginx-reverse-proxy | 2018/04/06 11:50:00 [emerg] 1#1: "log_format" directive is not allowed here in /etc/nginx/conf.d/default.conf:10
nginx-reverse-proxy | nginx: [emerg] "log_format" directive is not allowed here in /etc/nginx/conf.d/default.conf:10

【问题讨论】:

  • 您不应该在同一个服务器块中拥有 HTTP 和 HTTPS 侦听器,而是为 HTTPS 创建一个单独的侦听器,包括所需的 SSL 密钥。

标签: http docker nginx logging


【解决方案1】:

这似乎与this question 重复。

该消息意味着您在不允许的地方有一个 http 指令,即

http {
    ...
}

您可能想改用server 块,即

server {
    listen 80 default_server;
    server_name test.com;
    root /var/www/test/;
    access_log /var/log/nginx/test.com.access.log;
}

【讨论】:

  • 但是如何在您提供的配置中记录 http 正文?
  • 如果您需要记录请求正文,您可以查看this question
  • 你能把你的整个 nginx 配置文件贴出来吗?也许在gist
  • 您提供的调试日志与要点不匹配,请更新您的问题以使其符合...如果我没有正确的调试信息,我无法为您提供那么好的帮助
【解决方案2】:

将 log_format 放在 server{} 块之外,因为不是每个指令都可以去任何地方。简单地说:

log_format testlog '$remote_addr - $remote_user [$time_local] '
               '"$request" $status $bytes_sent '
               '"$http_referer" "$http_user_agent" "$request_body"';

server {
 listen 80;
 listen 443 default_server ssl;
 access_log /var/log/nginx/test.com.access.log;

 location / {
  proxy_pass http://myapp:8080;
  proxy_buffering off;
 }
}

在此处记录:http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format“上下文:http”

http 上下文是顶级块,包含您的 server 块(通常您看不到它,因为它位于包含您的 .conf 的另一个文件中)

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 2015-04-26
    • 2012-03-13
    • 1970-01-01
    • 2013-07-10
    • 2011-10-01
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多