why ngx.var.bytes_sent is 0?
I want to print packages' byes in lua and in my nginx.conf is: location /test_lua{ .... content_by_lua' ngx.say("uri : ", ngx.var.uri) ngx.say("status : ", ngx.var.status) ngx.say("bytes sent: ", ngx.var.bytes_sent) ngx.say("body bytes sent: ", ngx.var.body_bytes_sent)
'; } The results of uri and status is OK,but ngx.var.bytes_sent and ngx.var.body_bytes_sent is always zero,I have seen nginx's access log,they are not zero.
can you help me ? Thanks!
try ngx.flush() after each line
but uri and status is ok without ngx.flush()
it's zero because no bytes were sent yet they are only buffered and sent all at once after your code completes (unless you use flush)
ngx.flush syntax: ngx.flush(wait?)
context: rewrite_by_lua_, access_by_lua_, content_by_lua*
Flushes response output to the client.
@rkearsley Actually the output is always buffered by Nginx's own output body filters and the buffer size can be controlled by the standard "postpone_output" directive, which is set to 1460 (bytes) by default :)
So the following Lua code snippet without calling ngx.flush() should also yield non-zero $bytes_sent and $body_bytes_sent values because it sends a big enough data chunk.
ngx.say("uri : ", ngx.var.uri)
ngx.say("status : ", ngx.var.status)
ngx.say(string.rep("a", 1460)) -- ensure we exceed Nginx's own output buffer!
ngx.say("bytes sent: ", ngx.var.bytes_sent)
ngx.say("body bytes sent: ", ngx.var.body_bytes_sent)
And yeah, calling ngx.eof() should be better for @firefoxbug 's specific example. I just want to make it clear that no full response buffering is going on here unless the HTTP 1.0 response buffering is enabled in ngx_lua :)
@firefoxbug you do not have to call ngx.flush() on every line of output, just call it right before you want to read $bytes_sent and $body_bytes_sent, for example,
ngx.say("uri : ", ngx.var.uri)
ngx.say("status : ", ngx.var.status)
ngx.flush()
ngx.say("bytes sent: ", ngx.var.bytes_sent)
ngx.say("body bytes sent: ", ngx.var.body_bytes_sent)
Then we can get something like this on the client side:
uri : /t
status : 200
bytes sent: 192
body bytes sent: 32
Best regards, -agentzh
consider it resolved.
adding , ngx.flush()) in access_by_lua didn't work. I am trying to get the byte sent back in response to write to file