How to debug lua code inside nginx config?

another troubleshooting tool for openresty is lua-resty-console, which allows you to check the lua variable, imported modules, call functions etc. all you have to do is to install it use luarocks and insert a few lines into you nignx.conf. launch the client and here you go.

[9] ngx(content)> ngx.config.prefix()
=> /workspace/lua-resty-console/
[10] ngx(content)> ngx.config.ngx_lua_version
=> 10011
[11] ngx(content)> ngx.config.nginx_configure()
=>  --prefix=/usr/local/Cellar/openresty/1.13.6.1/nginx --with-cc-opt='-O2 -I/usr/local/include -I/usr/local/opt/pcre/include -I/usr/local/opt/openresty-openssl/include' --add-module=../ngx_devel_kit-0.3.0 --add-module=../echo-nginx-module-0.61 ...


[12] ngx(content)> ngx.sha →→
ngx.sha1_bin()  ngx.shared.     
[12] ngx(content)> ngx.shared. →→
ngx.shared.mycache.    ngx.shared.metrics.  
[12] ngx(content)> c = ngx.shared.mycache
=> nil
[13] ngx(content)> c
=> { <userdata 1>,
  <metatable> = <1>{
    __index = <table 1>,
    add = <function 1>,
    delete = <function 2>,
    flush_all = <function 3>,
    flush_expired = <function 4>,
    get = <function 5>,
    get_keys = <function 6>,
    get_stale = <function 7>,
    incr = <function 8>,
    llen = <function 9>,
    lpop = <function 10>,
    lpush = <function 11>,
    replace = <function 12>,
    rpop = <function 13>,
    rpush = <function 14>,
    safe_add = <function 15>,
    safe_set = <function 16>,
    set = <function 17>
  }
}
[14] ngx(content)> c:set('a', 1)
=> true
[15] ngx(content)> c:get('a')
=> 1
[16] ngx(content)> c:get_keys()
=> { "a" }

Another option for Lua debugging in nginx (in addition to "printing") is to use a Lua IDE that supports remote debugging. I posted instructions on how this can be done with ZeroBrane Studio IDE. After you set it up, you get most of debugging functions you'd expect, like stepping, breakpoints, inspections of variables, stack traces, and a console to run Lua commands remotely.


When running under nginx, you should use ngx.log. E.g:

ngx.log(ngx.STDERR, 'your message here')

For a working example, see http://linuxfiddle.net/f/77630edc-b851-487c-b2c8-aa6c9b858ebb

For documentation, see http://wiki.nginx.org/HttpLuaModule#ngx.log