10

As stated in this answer, the $time_local variable in access log of Nginx means the end time of a request (or close to).

Then, is there some way to log the start time of a request in Nginx access log?

I've googled around but just can't find any references to achive this. Come on! Isn't this a very simple function for a web server? Do not tell me to subtract the $request_time from the $time_local ...

1
  • 1
    Haproxy has this feature ('option logasap') but nginx doesn't. Aug 21, 2013 at 10:34

3 Answers 3

2

I know this is an old question, but I think it deserves an update, for nginx>1.2.5 (as of July 2017 nginx stable is 1.13) this is now trivial

In the log use

start_time="$msec"

Or to add a header:

add_header X-Request-Start $msec

or for a proxy

proxy_set_header X-Request-Start $msec
5
  • 1
    The documentation says $msec is "time in seconds with a milliseconds resolution at the time of the log write", and AFAIU access logs are written when the request ends. Oct 30, 2018 at 15:46
  • 1
    I think you're confusing $msec in log messages with a variable of the same name added to headers. One think is certain - in this context it's not the time logs are written, as you say logs are written at the end of requests and this header is added before requests are proxied. Nginx would have to be able to predict the future to know when a request will end before it's proxied. Oct 30, 2018 at 21:49
  • But that's for the add_header/proxy_set_header alternatives, isn't it? I'm still confused about the first suggested alternative "in the log use start_time="$msec"". Oct 31, 2018 at 8:16
  • Yes, unless there's a way to write logs at the beginning rather than end of requests Oct 31, 2018 at 14:51
  • So. I've actually tried this now. The general idea "you have to set the start time manually somehow" is sound, but using headers did not work for me. What did work is using variables: In your location (or similar) put set $request_start $msec;; then you can use $request_start in your log_format.
    – wosc
    May 19, 2021 at 8:12
1

Well, there is a patch for nginx (https://gist.github.com/rkbodenner/318681#comment-610856) that exposes request start time as a variable.

I think it could be useful in your case.

1
  • Well, though the patch is a little bit too difficult for us newbie to understand and apply, it indicates that there's no such built-in feature in Nginx. Thx any way.
    – reniaL
    Sep 2, 2013 at 8:10
1

You can write $msec and $request_time to the log and use $msec - $request_time as the start time when parsing.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .