简体   繁体   中英

How to log http request body from nginx docker image?

I'm having a docker image with nginx.

I would like to log incoming requests.

My docker-compose file:

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

My nginx config:

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;
 }
}

When I try to replace access_log directive with following config:

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;

I'm getting:

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

Put the log_format outside the server{} block, because not every directive can go anywhere. Simply:

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;
 }
}

It is docuemnted here: http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format "Context: http"

http context is the top level block, the one that contains your server block (usually you don't see it because it is in another file that is including your .conf)

This seems to be a duplicate of this question .

The message means that you have an http directive somewhere it's not allowed, ie

http {
    ...
}

You probably want to use a server block instead, ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM