Поиск по сайту:

Мониторинг файлов журнала Nginx с помощью ngxtop в Ubuntu 20.04


На этой странице

  1. Предпосылки
  2. Установите ngxtop
  3. Как использовать ngxtop
  4. Заключение

ngxtop — это бесплатный гибкий инструмент с открытым исходным кодом для мониторинга веб-серверов Nginx в режиме реального времени. Он может анализировать журнал доступа Nginx и печатать информацию о количестве запросов, запрошенном URI, количестве запросов по коду состояния и многом другом. Это простой и удобный инструмент для мониторинга запросов, поступающих на веб-сервер Nginx.

В этой статье я покажу вам, как установить и использовать инструмент мониторинга ngxtop в Ubuntu 20.04.

Предпосылки

  • Сервер под управлением Ubuntu 20.04.
  • На вашем сервере настроен пароль root.

Установить нгкстоп

ngxtop — это инструмент на основе Python, поэтому вам потребуется установить в систему пакеты Python и PIP. Вы можете установить их с помощью Nginx, используя следующую команду:

apt-get install nginx python3 python3-pip -y

После установки вы можете установить пакет ngxtop с помощью PIP, как показано ниже:

pip3 install ngxtop

После установки ngxtop вы можете проверить версию ngxtop с помощью следующей команды:

ngxtop --version

Вы должны получить следующий результат:

xstat 0.1

Как использовать ngxtop

В этом разделе мы покажем вам, как использовать ngxtop для мониторинга веб-сервера Nginx.

Запустите команду ngxtop без каких-либо аргументов, чтобы отобразить сводку количества запросов, запрошенный URI, количество запросов по коду состояния.

ngxtop

Вы должны увидеть следующий экран:

Вы можете использовать параметр -l, чтобы указать журнал доступа, который вы хотите проанализировать.

ngxtop -l /var/log/nginx/access.log

Вы должны увидеть следующий экран:

Чтобы получить список основных IP-адресов, которые обращаются к вашему серверу Nginx, выполните следующую команду:

ngxtop --group-by remote_addr -l /var/log/nginx/access.log

Вы должны увидеть следующий экран:

Вы можете распечатать 10 запросов с наибольшим общим количеством байтов, отправленных с помощью следующей команды:

ngxtop --order-by 'avg(bytes_sent) * count' -l /var/log/nginx/access.log

Вы должны увидеть следующий экран:

ngxtop также позволяет анализировать файл журнала Apache с удаленного сервера. Вы можете сделать это с помощью следующей команды:

ssh  tail -f /var/log/apache2/access.log | ngxtop -f common

Чтобы получить список всех параметров, доступных в ngxtop, выполните следующую команду:

ngxtop --help

Вы должны увидеть следующий вывод:

ngxtop - ad-hoc query for nginx access log.

Usage:
    ngxtop [options]
    ngxtop [options] (print|top|avg|sum)  ...
    ngxtop info
    ngxtop [options] query  ...

Options:
    -l , --access-log   access log file to parse.
    -f , --log-format   log format as specify in log_format directive. [default: combined]
    --no-follow  ngxtop default behavior is to ignore current lines in log
                     and only watch for new lines as they are written to the access log.
                     Use this flag to tell ngxtop to process the current content of the access log instead.
    -t , --interval   report interval when running in follow mode [default: 2.0]

    -g , --group-by   group by variable [default: request_path]
    -w , --having   having clause [default: 1]
    -o , --order-by   order of output for default query [default: count]
    -n , --limit   limit the number of records included in report for top command [default: 10]
    -a  ..., --a  ...  add exp (must be aggregation exp: sum, avg, min, max, etc.) into output

    -v, --verbose  more verbose output
    -d, --debug  print every line and parsed record
    -h, --help  print this help message.
    --version  print version information.

    Advanced / experimental options:
    -c , --config   allow ngxtop to parse nginx config file for log format and location.
    -i , --filter   filter in, records satisfied given expression are processed.
    -p , --pre-filter  in-filter expression to check in pre-parsing phase.

Examples:
    All examples read nginx config file for access log location and format.
    If you want to specify the access log file and / or log format, use the -f and -a options.

    "top" like view of nginx requests
    $ ngxtop

    Top 10 requested path with status 404:
    $ ngxtop top request_path --filter 'status == 404'

    Top 10 requests with highest total bytes sent
    $ ngxtop --order-by 'avg(bytes_sent) * count'

    Top 10 remote address, e.g., who's hitting you the most
    $ ngxtop --group-by remote_addr

    Print requests with 4xx or 5xx status, together with status and http referer
    $ ngxtop -i 'status >= 400' print request status http_referer

    Average body bytes sent of 200 responses of requested path begin with 'foo':
    $ ngxtop avg bytes_sent --filter 'status == 200 and request_path.startswith("foo")'

    Analyze apache access log from remote machine using 'common' log format
    $ ssh remote tail -f /var/log/apache2/access.log | ngxtop -f common

Заключение

В приведенном выше руководстве вы узнали, как установить и использовать ngxtop в Ubuntu 20.04. Я надеюсь, что теперь вы можете легко отслеживать свой журнал Nginx из интерфейса командной строки.