如何从nginx docker镜像中记录http请求体?

时间:2018-04-06 11:04:47

标签: http docker nginx logging

我有一个使用nginx的泊坞窗图片。

我想记录传入的请求。

我的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

2 个答案:

答案 0 :(得分:1)

将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的文件中)< / p>

答案 1 :(得分:0)

这似乎与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;
}