Is it possible to include content of lua variable in nginx access log in openresty?

324 Views Asked by At

I need to calculate some value in lua block, and include result into nginx access log.

Something like this: somewhere in http block:

log_format extended escape=json .... "timestamp_ns": "$lua_timestamp_ns" ....;

Somewhere in log_by_lua_block:

ngx.var.lua_timestamp_ns = nginx.var.msec * 1000

However, my configuration becomes invalid if I include arbitrary variable into log_format:
unknown "lua_timestamp_ns" variable

I have tried to "declare" variable using map or set, but in either case nginx considers that config invalid. Is it possible at all to include some arbitrary value into access log at all?

1

There are 1 best solutions below

0
Dmitry Meyer On BEST ANSWER

The following configuration should work:

http {
    log_format extended escape=json 'timestamp_ns: $lua_timestamp_ns';

    server {
        access_log /dev/stdout extended;

        # this line is required to create the variable at config time,
        # see: https://github.com/openresty/lua-nginx-module#ngxvarvariable
        set $lua_timestamp_ns '';

        log_by_lua_block {
            ngx.var.lua_timestamp_ns = ngx.var.msec * 1000
        }
    }
}