nginx 日志和監控


Logging and Monitoring 日志和監控

This section describes how to configure logging of errors and processed requests, as well as how to use the runtime monitoring service of NGINX and NGINX Plus.

本文學習,如何配置錯誤日志與處理請求,以及如何使用NGINX和NGINX+的實時監控服務。

In This Section  本章有

Setting Up the Error Log 搭建錯誤日志

NGINX writes information about encountered issues of different severity levels to the error log. The error_log directive sets up logging to a partifular file, stderr, or syslog and specifies the minimal severity level of messages to log. By default, the error log is located at logs/error.log (the absolute path depends on the operating system and installation), and messages from all severity levels above the one specified are logged.

Nginx把遇到的不同級別的問題信息寫到錯誤日志。error_log 指令配置記錄到特定的文件,stderr,或者syslog,配置寫到日志的最低級別信息。默認地,錯誤日志位於logs/error.log(絕對路徑取決於操作系統和安裝方式),比指定級別更高級別的信息都將被記錄。

The configuration below changes the minimal severity level of error messages to log from error to warn.

下面這個配置把記錄到日志的錯誤信息的最低級別由 error 改為 warn。

error_log logs/error.log warn;

In this case messages of warnerrorcritalert, and emerg levels will be logged.

這樣warn, error, crit, alert, emger 級別的信息都會被記錄。

The default setting of the error log works globally. To override it, the error_log directive should be placed in the main context. The settings of the main context are always inherited by other levels. The error_log directive can be specified on other levels too, cancelling the effect inherited from the higher levels. In case of an error, the message will be written to only one error log. This log will be the closest to the level where the error has occurred. However, if several error_log directives are specified on the same level, the message will be written to to all logs specified.

默認的錯誤日志設置是全局的。要覆蓋它,error_log 指令必須放在main環境中。man環境里的設置都會被其他層繼承。error_log指令也可以在其他層里指定,以取消從更高層繼承下來的。如果發生一個錯誤,信息只會被寫到一個錯誤日志。這個日志將寫到錯誤發生的最近的那一層。然而,如果在同一個層定義了多個error_log指令,信息會被寫到所有指定的日志文件。

Note: Using several error log directives at the same level are supported in NGINX versions 1.5.2 and greater.

注意:同一層使用多個錯誤日志需要Nginx版本為1.5.2或更高。

 

Setting Up the Access Log 設置訪問日志

To the access a log, NGINX writes information about client requests after the request is processed. By default, the access log is located at logs/access.log, and the information is written to the log in the predefined, combined format. To override the default setting, use the log_format directive to configure a format of logged messages, as well as the access_log directive to specify the location of the log and the format. The format is defined using variables.

Nginx處理請求后把關於客戶端請求的信息寫到訪問日志。默認,訪問日志位於 logs/access.log,寫到日志的信息是預定義的、組合的格式。要覆蓋默認的配置,使用log_format指令來配置一個記錄信息的格式,同樣使用access_log 指令到設置日志和格式和位置。格式定義使用變量。

The following examples define a format that extends the standard combined format with the value indicating the ratio of gzip compression of the response. The format is then applied to a virtual server that enables compression.

下面這個例子定義一個格式,這個格式在標准組合格式上進行擴展加入對響應進行gzip壓縮的比率的值。該格式被應用於一個開啟了壓縮的虛擬服務器。

 

  1. http {  
  2.     log_format compression '$remote_addr - $remote_user [$time_local] '  
  3.                            '"$request" $status $body_bytes_sent '  
  4.                            '"$http_referer" "$http_user_agent" "$gzip_ratio"';  
  5.   
  6.     server {  
  7.         gzip on;  
  8.         access_log /spool/logs/nginx-access.log compression;  
  9.         ...  
  10.     }  
  11. }  
http {
    log_format compression '$remote_addr - $remote_user [$time_local] '
                           '"$request" $status $body_bytes_sent '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';

    server {
        gzip on;
        access_log /spool/logs/nginx-access.log compression;
        ...
    }
}

 

Logging can be optimized by enabling the buffer for log messages and the cache of descriptors of frequently used log files whose names contain variables. To enable buffering use the buffer parameter of the access_log directive to specify the size of the buffer. The buffered messages are then written to the log file when the next log message does not fit into the buffer as well as in some other cases. To enable caching of log file descriptors, use the open_log_file_cache directive.

開啟日志信息緩沖,被頻繁使用且名字包含變量的文件的操作的緩存,能夠優化日志記錄。要開始緩沖,使用access_log指令的buffer參數來指定緩沖的大小。緩沖區里的信息在緩沖區不夠寫下一個信息時以及另外的一些情況下寫入日志文件。要開啟文件操作的緩存,使用open_log_file_cache指令。

Similar to the error_log directive, the access_log directive defined on a level overrides the settings from the previous levels. When processing of a request is completed, the message is written to the log that is configured on the current level, or inherited from the previous levels. If one level defines multiple access logs, the message is written to all of them.

與error_log指令相似, 定義了access_log指令的層將會把從上一層繼承下來的設置覆蓋。當一個請求的處理完畢,信息被寫到由當前層定義或者從上層繼承下來的日志文件中。如果一個層里定義了多個訪問日志,信息會被寫到所有日志中。

Enabling Conditional Logging 開啟有條件的日志記錄

Conditional logging allows excluding trivial or non-important log entries from the access log. In NGINX, conditional logging is enabled by the if parameter of the access_log directive.

根據條件的日志記錄能不記錄細枝末節和不重要的日志條目到訪問日志中。在Nginx中,條件性日志記錄使用access_log指令的 if 參數開啟。

For example, it makes possible to exclude requests with HTTP status codes 2XX (Success) and 3XX (Redirection):

例如,可以把狀態碼以2和3開頭的HTTP請求忽略不計:

 

  1. map $status $loggable {  
  2.     ~^[23]  0;  
  3.     default 1;  
  4. }  
  5. access_log /path/to/access.log combined if=$loggable;  
map $status $loggable {
    ~^[23]  0;
    default 1;
}
access_log /path/to/access.log combined if=$loggable;

 

Logging to Syslog 記錄到系統日志

Syslog is a standard for computer message logging and allows collecting log messages from different devices on a single syslog server. In NGINX, logging to syslog is configured with the syslog: prefix in error_log and access_log directives.

系統日志是一個計算機信息記錄標准,能夠記錄來自不同設備的日志信息到一個單一的系統日志服務器。在Nginx中,記錄到系統日志要在error_log 和 access_log指令中加前綴  syslog: 來配置。

Syslog messages can be sent to a server= which can be a domain name, an IP address, or a UNIX-domain socket path. A domain name or IP address can be specified with a port, by default port 514 is used. A UNIX-domain socket path can be specified after the unix: prefix:

系統日志信息能被發送到一個server=,server=后面可以是一個域名,一個IP地址或者一個unix-domain套接字路徑。域名或者ip地址能指定端口,默認端口為514,unix-domain套接字路徑跟在前綴unix:后:

 

  1. error_log server=unix:/var/log/nginx.sock debug;  
  2. access_log syslog:server=[2001:db8::1]:1234,facility=local7,tag=nginx,severity=info;  
error_log server=unix:/var/log/nginx.sock debug;
access_log syslog:server=[2001:db8::1]:1234,facility=local7,tag=nginx,severity=info;

 

In the example, NGINX error log messages will be written to UNIX domain socket with the debug logging level, and the access log will be written to a syslog server with IPv6 address and port 1234.

本例中,Nginx錯誤日志消息以debug日志級別記錄到 UNIX 域套接字,訪問日志將被記錄到一個IPv6地址商品為1234的系統日志服務器。

The facility= parameter specifies the type of program which is logging the message. The default value is local7. Other values may be: authauthprivdaemoncronftplprkernmail,newssysloguseruucplocal0  … local7.

參數facility=指定記錄日志消息的程序類型。缺省值為local7,其他可用值有: authauthprivdaemoncronftplprkernmail,newssysloguseruucplocal0  … local7.

The tag= parameter will apply a custom tag to syslog messages, in our example the tag is nginx.

參數tag=在系統日志消息中應用一個自定義標簽,上例中標簽為nginx。

The severity= parameter sets the severity level of syslog messages for access log. Possible values in order of increasing severity are: debuginfonoticewarnerror (default), critalert, and emerg. In our example, the severity level error will also enable critalert, and emerg levels to be logged.

參數severity=設置訪問日志的系統日志消息的嚴重級別。可使用的值按嚴重級別順序遞增為:debuginfonoticewarnerror (default), critalert, and emerg。我們的例子中,嚴重級別error將開啟crit, alert, emerg  級別的記錄。

Live Activity Monitoring 實時活動監控

NGINX Plus provides a real-time activity monitoring interface that shows key load and performance metrics of your upstream servers as well as other data including:

Nginx + 提供一個實時活動監控界面,展示鍵的負載和上游服務器的性能指標,以及其他數據包括:

  • NIGNX basic version, uptime and identification information;
  • Nginx基礎版本,運行時間和認證信息;
  • total and current numbers of connections and requests;
  • 連接和請求的當前數目以及總數目;
  • request and response counts for each status_zone;
  • 每個status_zone的請求和響應數;
  • request and response counts per server in each dynamically configured groups of servers, plus health-check and uptime statistics;
  • 每個服務器動態配置組的請求和響應數,還有健康檢測和正常運行時間統計;
  • statistics per server, including its current state and total values (total fails etc.)
  • 統計每個服務器,包含當前狀態和總體值(總體失敗次數等)。
  • instrumentation for each named cache zone.
  • 每個命名過的緩存空間的檢測表。

The complete list of metrics is available here.

性能指標的完整列表點擊此處

 

The statistics can be viewed from the status.html page already included in each NGINX Plus package. The page polls status information and displays it in a simple table:

統計數據可以從status.html頁面查看,該頁面已包含在每個Nginx+的包里。頁面統計狀態信息並且展示在一個簡單的表里:http://demo.nginx.com/status.html

And using a simple RESTful JSON interface, it’s easy to connect these stats to live dashboards and third-party monitoring tools.

還可以使用一個簡單的 RESTful JSON 接口,可以通過第三方監控平台輕松連接這些狀態做一個實時儀表盤。

Enabling Activity Monitoring 開啟活動監控

To enable real-time activity monitoring and the JSON interface, you must specify the location that checks the exact match of the URI with /status and contains the status directive. To enable the status.html page, you must specify one more location that sets it:

要開啟實時活動監控和 JSON 接口,必須在精確匹配 /status 的 location 里包含 status 指令。要啟用status.html頁面,你必須在至少一個location里設置它:

 

  1. server {  
  2.     listen 127.0.0.1;  
  3.     root /usr/share/nginx/html;  
  4.   
  5.     location /status {  
  6.         status;  
  7.     }  
  8.   
  9.     location = /status.html {  
  10.     }  
  11. }  
server {
    listen 127.0.0.1;
    root /usr/share/nginx/html;

    location /status {
        status;
    }

    location = /status.html {
    }
}

With the following configuration, the webpage status.html located at /usr/share/nginx/html can be requested by the URL http://127.0.0.1/status.html.

 

根據這個配置,網頁status.html位於/usr/share/nginx/html能通過URL http://127.0.0.1/status.html 訪問到。

Using RESTful JSON Interface 使用 RESTful JSON 接口

NGINX Plus stats can be easlily connected to third-party applications, such as performance dashboards. This can be done with the JSON interface.

Nginx+的統計能輕松連接到第三方應用,比如性能儀表盤。可以通過JSON接口實現。

If you request /status (or whichever URI matches the location group), then NGINX Plus will respond with a JSON document containing the current activity data.

如果你請求/status(或者任何一個能匹配這個location 組的URI),Nginx+將響應一個包含當前活動數據的JSON文檔。

The status information of any element in the JSON document can be requested by a slash-separated URL:

JSON文檔的每一個元素的狀態信息都可以通過在請求后用斜線分隔的URL來請求:

http://127.0.0.1/status http://127.0.0.1/status/nginx_version http://127.0.0.1/status/caches/cache_backend http://127.0.0.1/status/upstreams http://127.0.0.1/status/upstreams/backend http://127.0.0.1/status/upstreams/backend/1 http://127.0.0.1/status/upstreams/backend/1/weight

To learn more about NGINX Plus, please see the descriptions of our commercial subscriptions.

更多關於NGINX+的信息,主參閱我們的商業訂閱


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM