apache httpd log 檔案格式

2020091415:05


httpd.conf 中

apache httpd Log 的標準格式是:
LogFormat "%h %l %u %t \"%r\" %>s %b" common

記錄檔就像這樣:
172.69.34.195 - - [08/Sep/2020:15:44:57 +0800] "GET /favicon.ico HTTP/1.1" 404 196
172.69.33.228 - - [08/Sep/2020:15:45:01 +0800] "GET /images/scrolltotop.png HTTP/1.1" 200 5550
108.162.215.109 - - [08/Sep/2020:15:40:18 +0800] "GET /images/2019.mp4 HTTP/1.1" 206 3423313


若 web server 前端有加上 proxy 或是 CDN (如cloudflare),可以加上 %{X-Forwarded-For}i 來記錄 user 的真實 IP:
LogFormat "%h %{X-Forwarded-For}i %l  %u %t \"%r\" %>s %b elapsed=%Dus" common2
      


記錄檔就像這樣:
172.69.134.246 1.171.15x.xx  - [14/Sep/2020:15:04:13 +0800] "GET /images/header_bg.png HTTP/1.1" 200 5182 elapsed=22048us
172.69.134.72 1.171.15x.xx -  [14/Sep/2020:15:04:13 +0800] "GET /images/footer_bg.jpg HTTP/1.1" 200 24829 elapsed=113512us
162.158.165.51 1.171.15x.xx -  [14/Sep/2020:15:04:13 +0800] "GET /favicon.ico HTTP/1.1" 404 196 elapsed=3177us


**要找出 log 中,時間大於 1秒的方法:
 cat access_log | awk -F\" '{print $NF,$2,$1}' | awk '{print $1,$3,$5,$8}'| sed 's/us=//' \
 | sed 's/us//' | awk '{if ($1 > 500) {print $1, $4, $3, $2}}' |sort -nr



一些常用的變數:
%{X-Forwarded-For}i 

如果想紀錄 php 的執行時間,可以用 %D
%D 程式(如 php)的執行時間或是 httpd 讀取檔案花費的時間,單位 us 百萬分之一秒
     %D 不包含這個檔案傳輸花費的時間
     只會紀錄 httpd 正確收到一個 requst 開始 到 httpd執行完php(或讀取完一個圖檔)準備要送出資料 的時間
     若有開啟 deflate_module 壓縮功能,則 httpd 處理壓縮時間也會被加到 %D 裏頭
    
%{User-Agent}i  用戶的瀏覽器名稱 (User Agent)
%{Referer}i


===
關於時間的紀錄

%t
  Time the request was received, in the format [18/Sep/2011:19:18:28 -0400]. The last number indicates the timezone offset from GMT
%t 的標準時間格式
[23/Jun/2020:08:54:24 +0800]

若覺得秒數不夠精確
可記錄千分之一秒 (毫秒 millisecond ):
%{format}t
The time, in the form given by format, which should be in an extended strftime(3) format (potentially localized).
If the format starts with begin: (default) the time is taken at the beginning of the request processing.
If it starts with end: it is the time when the log entry gets written, close to the end of the request processing.
In addition to the formats supported by strftime(3), the following format tokens are supported:

sec  number of seconds since the Epoch
msec number of milliseconds since the Epoch
usec  number of microseconds since the Epoch
msec_frac  millisecond fraction
usec_frac  microsecond fraction

These tokens can not be combined with each other or strftime(3) formatting in the same format string. You can use multiple %{format}t tokens instead.
 
[%{%d/%b/%Y %T}t.%{msec_frac}t %{%z}t]

記錄檔的結果像這樣:
[23/Jun/2020 08:58:08.712 +0800]
 
甚至更精確的百萬分之一秒 (微秒 microsecond )
[%{%d/%b/%Y %T}t.%{usec_frac}t %{%z}t]

記錄檔的結果像這樣:
[23/Jun/2020 09:00:54.451034 +0800]


若要一個 request 紀錄起、訖時間
可以加上 begin:  / end:
%{%d/%b/%Y %T}t.%{begin:usec_frac}t %{%d/%b/%Y %T}t.%{end:usec_frac}t

記錄檔的結果像這樣:
11/Oct/2021 11:45:19.877348 11/Oct/2021 11:45:19.878292

===

參考
https://httpd.apache.org/docs/2.4/mod/mod_log_config.html