Статьи

Регистрация JSON в Apache и Nginx с помощью Logentries

[Эта статья была написана Томом Смитом.]

Меня часто спрашивают по телефону с нашими клиентами, какой формат предпочитается для отправки данных журнала в Logentries. Хотя мы гордимся тем, что являемся инструментом управления журналами, который проще всего настраивать и использовать, некоторые очень важные расширенные функции платформы доступны для журналов, отформатированных в пару значений ключа (KVP)  или JSON. Большинство приложений и языков программирования имеют возможность изменять свой формат регистрации. Немного поработав, вы сможете раскрыть весь потенциал наших расширенных функций поиска . Ниже мы обсудим настройку Apache и Nginx для отправки JSON отформатированные журналы и способы использования функций поиска, общих панелей мониторинга и возможностей отчетности на платформе Logentries.

апаш

В Apache2 формат доступа и журнала ошибок по умолчанию выглядит следующим образом:

127.0.0.1 - - [11/Aug/2014:16:44:00 +0000] "GET / HTTP/1.0" 200 11783 "-" "ApacheBench/2.3"

Эта запись в журнале определенно содержит очень важную информацию. Но потратив всего 5 минут на настройку Apache, информация о регистрации будет содержать гораздо больше полезной информации.

Начните с редактирования файла apache2.conf для вашего сайта / сервера, который находится в / etc / apache2. Добавьте следующую строку кода в область LogFormat (см. Снимок экрана ниже).

Как только это будет настроено, вам нужно отредактировать файл default.conf для каждого сайта в вашей конфигурации Apache. В этом случае мы хотим изменить тип журнала access.log на leapache. Например:

После завершения перезапустите Apache, и теперь логирование будет выглядеть так:

{ "time":"[11/Aug/2014:17:21:45 +0000]", "remoteIP":"127.0.0.1", "host":"localhost",
"request":"/index.html", "query":"", "method":"GET", "status":"200", 
"userAgent":"ApacheBench/2.3", "referer":"-" }

Nginx

The Nginx configuration is almost exactly the same as the Apache2 configuration. To configure Nginx to log in JSON format, add the following lines to the #Logging Settings section of your nginx.conf (usually found in /etc/nginx).

log_format le_json '"time": "$time_iso8601", '
             '"remote_addr": "$remote_addr", '
             '"remote_user": "$remote_user", '
             '"body_bytes_sent": "$body_bytes_sent", '
             '"request_time": "$request_time", '
             '"status": "$status", '
             '"request": "$request", '
             '"request_method": "$request_method", '
             '"http_referrer": "$http_referer", '
             '"http_user_agent": "$http_user_agent"';
 
       access_log /var/log/nginx/access.log le_json;

Restart Nginx and your logging will now be in JSON format. The log entries will now look like this:

"time": "2014-08-11T11:40:13+00:00", "remote_addr": "122.226.223.69", "remote_user": "-",
"body_bytes_sent": "579", "request_time": "0.000", "status": "404", "request": "GET
http://www.k2proxy.com//hello.html HTTP/1.1", "request_method": "GET", "http_referrer": "-",
"http_user_agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; 
.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"

Search and Functions in Logentries

Now that we have our logs formatted in a more machine-readable format, we can get to the fun part! Start out by sending these logs to Logentries if you’re not already. Login to your account and access the logs within the UI. Try typing the following search into the search bar:

status groupby(status) calculate(COUNT)

This will result in a graph being created, showing you the status distribution over the period of time selected.

Other search functions are available as well:

Count: Produces a graph and chart of a count of all instances of the search term over the provided time.  (e.g., status =200 calculate(COUNT))

SUM: Produces a graph and chart that sums all instances of the search term over the provided time.  (e.g., bytes_sent>0 calculate(SUM))

Average: Produces a graph and chart (below) that averages out the KVP item you’re searching for over the provided time. (e.g., req_time >0 calculate(AVERAGE))

Count Unique: Gives you a view of unique log lines of your KVP item over the provided time. (e.g., status=200 calculate(UNIQUE:ip))

These searches can be saved as either a saved search and turned into graphs or a Tag to be alerted on at a later time. Using all that we’ve learned through the search functions, creating shareable dashboards, and sharing information to third party tools such as Geckoboard, you can now easily view, share, and analyze your logs like never before!