lua-nginx-module icon indicating copy to clipboard operation
lua-nginx-module copied to clipboard

why ngx.var.bytes_sent is 0?

Open firefoxbug opened this issue 13 years ago • 8 comments

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!

firefoxbug avatar Jun 07 '13 07:06 firefoxbug

try ngx.flush() after each line

rkearsley avatar Jun 07 '13 07:06 rkearsley

but uri and status is ok without ngx.flush()

firefoxbug avatar Jun 07 '13 08:06 firefoxbug

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)

rkearsley avatar Jun 07 '13 08:06 rkearsley

ngx.flush syntax: ngx.flush(wait?)

context: rewrite_by_lua_, access_by_lua_, content_by_lua*

Flushes response output to the client.

phonehold avatar Jun 07 '13 09:06 phonehold

@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 :)

agentzh avatar Jun 07 '13 16:06 agentzh

@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

agentzh avatar Jun 07 '13 17:06 agentzh

consider it resolved.

agentzh avatar Sep 08 '13 03:09 agentzh

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

rest17 avatar Apr 24 '20 01:04 rest17