Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging a variable set by nginx's Lua module

Tags:

nginx

lua

I am trying to use the Lua module in nginx to set a variable ("foo") based on JSON in the body of a request. Then I want to log the value of that variable to the access log.

Like so:

http {
    log_format mylogfmt '$remote_addr - $remote_user [$time_local] \
        "$request" $status $body_bytes_sent "$http_referer" \
        "$http_user_agent" "$foo"'
}

location / {
    proxy_pass http://remote-server.example.com/;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_connect_timeout 150;
    proxy_send_timeout 100;
    proxy_read_timeout 100;
    proxy_buffers 4 32k;
    client_max_body_size 8m;
    client_body_buffer_size 128k;

    rewrite_by_lua '
        cjson = require "cjson"
        ngx.req.read_body()
        body_table = cjson.decode(ngx.var.request_body)
        ngx.var.foo = body_table["foo"]
    ';

    access_log /var/log/nginx/access.log mylogfmt;
}

However, nginx won't start with this configuration. It complains thusly:

danslimmon@whatever:~$ sudo /etc/init.d/nginx reload
Reloading nginx configuration: nginx: [emerg] unknown "foo" variable
nginx: configuration file /etc/nginx/nginx.conf test failed

I tried adding a 'set $foo "-"' to the location, but that just seems to override what I'm doing in Lua.

Thoughts?

My nginx -V output

like image 348
danslimmon Avatar asked Jul 15 '13 20:07

danslimmon


1 Answers

You need to define the variable $foo before the Lua module can use it. Check the doc for an example defining the variable within the location directive before utilizing it.

like image 137
Edd Avatar answered Nov 24 '22 00:11

Edd