pgbadger

pgbadger — инструмент для быстрого анализа журналов Postgres Pro с созданием подробных отчётов и графиков

Синтаксис

pgbadger [параметр_подключения...] [параметр...] [файл_журнала...]

Описание

pgbadger — это анализатор журналов Postgres Pro/PostgreSQL, который быстро строит подробные отчёты, обрабатывая файлы журналов сервера. pgbadger поставляется вместе с Postgres Pro как отдельный скрипт на языке Perl.

В качестве файла_журнала можно передать отдельный файл, список файлов, или команду, выдающую список файлов. Если передать «-», содержимое журнала будет считываться из стандартного ввода.

Анализатор запросов pgbadger может обрабатывать огромные файлы журналов и сжатые файлы. Он может автоматически определять формат файла журнала (syslog, stderr, csvlog или jsonlog), если файл достаточно большой. Поддерживаемые форматы сжатия: gzip, bzip2, lz4, xz, zip и zstd. Для формата xz у вас должна быть установлена версия xz выше 5.05, которая поддерживает параметр --robot. Чтобы pgbadger определял размер несжатого файла для формата lz4, файл должен быть сжат с использованием параметра --content-size.

pgbadger поддерживает любой формат префиксов строк журнала, который можно задать в параметре log_line_prefix в файле конфигурации postgresql.conf, при условии, что указаны как минимум %t и %p.

Также могут быть проанализированы файлы журналов pgbouncer.

Для ускорения разбора журнала можно использовать режимы многопоточной обработки: выделять несколько ядер для нескольких файлов журнала или несколько ядер для одного файла. Эти режимы также можно сочетать.

pgbadger также может анализировать удалённые файлы журналов, получаемые через SSH-соединение без пароля. Этот режим может использоваться со сжатыми файлами и даже поддерживает многопоточность с выделением нескольких ядер на файл.

Примеры отчётов можно найти на странице https://pgbadger.darold.net/#reports.

Ограничения #

pgbadger в настоящее время имеет следующие ограничения:

  • Многопоточная обработка не поддерживается при чтении сжатых файлов журналов и CSV-файлов, а также в Windows.

  • Файлы журналов формата CSV не могут быть обработаны удалённо.

  • Журналы csvlog не могут быть переданы из стандартного ввода.

Подготовка и настройка #

pgbadger поставляется вместе с Postgres Pro Enterprise в виде отдельного пакета pgbadger (подробные инструкции по установке приведены в Главе 17). Установив pgbadger, настройте его, как описано далее.

Подготовка для обработки определённых форматов журнала (необязательно)

Если вы планируете анализировать файлы журналов CSV, установите Perl-модуль Text::CSV_XS.

Подготовка для экспорта статистики (необязательно)

Если вы хотите экспортировать статистику в формате JSON, установите Perl-модуль JSON::XS:

Чтобы установить этот дополнительный модуль:

  • В системах на базе Debian запустите:

    sudo apt-get install libjson-xs-perl
  • В RPM-системе запустите:

    sudo yum install perl-JSON-XS

Подготовка для обработки сжатых файлов журнала (необязательно)

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

  • zcat для gz

  • bzcat для bz2

  • lz4cat для lz4

  • zstdcat для zst

  • unzip или xz для zip или xz

Если необходимая утилита находится вне каталогов, указанных в PATH, задайте путь к ней в параметре командной строки --zcat. Например:

--zcat="/usr/local/bin/gunzip -c" или --zcat="/usr/local/bin/bzip2 -dc"
--zcat="C:\tools\unzip -p"

Примечание

Благодаря автоопределению формата сжатых файлов вы можете использовать разные форматы журналов gz, bz2, lz4, xz, zip и zstd. Однако если вы зададите своё значение --zcat, обрабатывать сжатые файлы разных форматов не получится.

Настройка сервера Postgres Pro

Установите определённые параметры конфигурации в файле postgresql.conf:

  • Настройте журналирование SQL-запросов.

    Чтобы включить журналирование SQL-запросов и получать в статистике запросов собственно текст этих запросов, установите

    log_min_duration_statement = 0

    На нагруженном сервере вы можете задать ненулевое значение, чтобы в журнал вносились только запросы с большей продолжительностью.

    Если вам нужна только информация о продолжительности и количестве запросов, а не подробные сведения о них, установите для log_min_duration_statement значение -1, при котором запись операторов по длительности отключается, и включите log_duration.

    При включении log_min_duration_statement добавятся отчёты о самых медленных запросах и запросах, которые заняли больше всего времени. Обратите внимание: если вы установите для log_statement значение all, параметр log_min_duration_statement не будет работать.

    Предупреждение

    Не устанавливайте для log_min_duration_statement неположительные значения одновременно с включением log_duration и log_statement, так как в результате нарушится подсчёт запросов и значительно увеличится размер журнала. Всегда предпочтительнее устанавливать log_min_duration_statement.

  • Установите префикс строк журнала в log_line_prefix.

    Он должен включать как минимум спецпоследовательность времени (%t, %m или %n) и спецпоследовательность, идентифицирующую процесс (%p или %c). Например, для журналов stderr параметр должен содержать как минимум

    log_line_prefix = '%t [%p]: '

    В префикс строк журнала также можно добавить имя пользователя, базы данных, приложения и IP-адрес клиента. Например

    для журналов stderr:

    log_line_prefix = '%t [%p]: user=%u,db=%d,app=%a,client=%h '

    или

    log_line_prefix = '%t [%p]: db=%d,user=%u,app=%a,client=%h '

    и для журналов syslog:

    log_line_prefix = 'user=%u,db=%d,app=%a,client=%h '

    или

    log_line_prefix = 'db=%d,user=%u,app=%a,client=%h '
  • Чтобы получить больше информации из файлов журналов, задайте следующие параметры конфигурации:

    log_checkpoints = on
    log_connections = on
    log_disconnections = on
    log_lock_waits = on
    log_temp_files = 0
    log_autovacuum_min_duration = 0
    log_error_verbosity = default

    Чтобы этот набор параметров работал, не включайте log_statement, так как pgbadger не сможет разобрать получившийся журнал.

  • Установите язык, на котором сервер будет выводить сообщения; сообщения должны быть на английском языке с поддержкой локали или без неё:

    lc_messages='C'

    или

    lc_messages='en_US.UTF-8'

    Локали других языков, например ru_RU.utf8, не поддерживаются.

Использование #

Ниже приведены простые примеры, иллюстрирующие различные аспекты использования pgbadger.

pgbadger /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger /var/lib/pgpro/ent-18/data/log/postgres.log.2.gz /var/lib/pgpro/ent-18/data/log/postgres.log.1.gz /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger /var/lib/pgpro/ent-18/data/log/postgresql/postgresql-2022-01-*
pgbadger --exclude-query="^(COPY|COMMIT)" /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger -b "2022-01-25 10:56:11" -e "2022-01-25 10:59:11" /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-25-0000.log 
cat /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log | pgbadger -
# Префикс строк журнала, выводимого в stderr
pgbadger --prefix '%t [%p]: user=%u,db=%d,client=%h' /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21*
pgbadger --prefix '%m %u@%d %p %r %a : ' /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21-0000.log
# Префикс строк журнала, выводимого в syslog
pgbadger --prefix 'user=%u,db=%d,client=%h,appname=%a' /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21*
# Использовать 8 ядер для ускорения обработки 10-гигабайтного файла
pgbadger -j 8 /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21-0000.log
# Задание cron, которое еженедельно формирует отчёт об ошибке
30 23 * * 1 /usr/bin/pgbadger -q -w /var/lib/pgpro/ent-18/data/log/postgresql-2022-01*.log -o /var/www/pg_reports/pg_errors.html

Указание удалённых файлов журнала

Удалённые файлы журналов для анализа задаются посредством URI. Поддерживаемые протоколы: HTTP[S] и [S]FTP. Для загрузки файлов будет использоваться команда curl, и разбираться они будут сразу во время загрузки. Также поддерживается протокол SSH, в этом случае для загрузки файлов применяется команда ssh, как и при использовании параметра --remote-host.

Для указания удалённых файлов журналов вы можете использовать такие URI:

pgbadger http://172.12.110.1//var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger ftp://username@172.12.110.14/postgresql-2022-01-14_000000.log
pgbadger ssh://username@172.12.110.14:2222//var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log*

Также возможно обрабатывать одновременно и локальные, и удалённые файлы журналов Postgres Pro (в том числе, журнал pgbouncer):

pgbadger /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log ssh://username@172.12.110.14/pgbouncer.log  

Параллельная обработка

Чтобы включить параллельную обработку, укажите параметр -j N, где N — количество используемых ядер.

Параллельная обработка в pgbadger выполняется по следующему алгоритму:

Для каждого файла журнала
   размер порции = int(размер файла / N)
   определить начальное/конечное смещение этих порций
   породить N процессов и искать начальное смещение каждого фрагмента
     завершать каждый процесс разбора по достижении конечного смещения его фрагмента
     записать статистику, собранную процессом, во временный бинарный файл
   дождаться завершения всех дочерних процессов
Затем все сгенерированные бинарные временные файлы считываются и загружаются в
память для формирования выходного html.

Когда применяется этот метод, pgbadger может усечь или пропустить в начале/конце порций максимум N запросов на файл журнала, что вряд ли имеет значение, если в вашем файле журнала миллионы запросов. Вероятность того, что потеряется именно интересующий вас запрос, близка к нулю, так что потерю такого объёма можно считать приемлемой. В большинстве случаев запрос учитывается дважды, но в усечённом виде.

Если у вас много небольших файлов журналов и много ядер, для ускорения лучше выделить одно ядро на один файл журнала. Чтобы включить такое поведение, укажите параметр -J N. Таким образом, вы можете быть уверены, что не потеряете ни одного запроса в отчётах. Например, если обрабатывать 200 файлов по 10 Мбайт каждый, параметр -J начинает показывать свою эффективность с 8 ядрами.

Ниже представлены результаты теста, полученные при обработке на сервере с 8 ядрами одного файла размером 9,5 гигабайт.

 Параметр | 1 ядро  |  2 ядра |  4 ядра | 8 ядер
----------+---------+---------+---------+--------
   -j     | 1h41m18 |  50m25  |  25m39  | 15m58
   -J     | 1h41m18 |  54m28  |  41m16  | 34m45

С 200 файлами журналов по 10 мегабайт каждый, что в сумме составляет 2 гигабайта, результаты немного отличаются:

 Параметр |  1 ядро | 2 ядра | 4 ядра | 8 ядер
----------+---------+--------+--------+--------
   -j     |  20m15  |  9m56  |  5m20  | 4m20
   -J     |  20m15  |  9m49  |  5m00  | 2m40

Поэтому рекомендуется использовать -j, кроме случаев, когда нужно обработать сотни небольших файлов и имеется минимум 8 ядер.

Важно

Во время параллельной обработки pgbadger создаёт множество временных файлов с именами tmp_pgbadgerXXXX.bin в каталоге /tmp и удаляет их в конце.

Создание инкрементальных отчётов

Следующий пример задания cron демонстрирует создание отдельных еженедельных отчётов, в предположении, что осуществляется еженедельная ротация файлов журналов:

0 4 * * 1 /usr/bin/pgbadger -q `find /var/lib/pgpro/ent-18/data/log/ -mtime -7 -name "postgresql.log*"` -o /var/www/pg_reports/pg_errors-`date +\%F`.html -l /var/reports/pgbadger_incremental_file.dat

Вы можете включить режим автоматического создания инкрементальных отчётов pgbadger, воспользовавшись параметром -I/--incremental. В этом режиме pgbadger создаёт один отчёт в день и один накопительный отчёт в неделю. Результаты обработки журналов сначала сохраняются в двоичном формате, в каталоге, задаваемом параметром -O/--outdir, а затем строятся ежедневные и еженедельные HTML-отчёты с индексным файлом. В индексном файле отображаются раскрывающиеся меню по неделям со ссылкой на недельный отчёт и ссылками на отчёты по дням недели. Например, вы можете запустить pgbadger с ежедневной ротацией файла следующим образом:

0 4 * * * /usr/bin/pgbadger -I -q /var/lib/pgpro/ent-18/data/log/postgresql/postgresql.log.1 -O /var/www/pg_reports/

Вы получите все ежедневные и еженедельные отчёты. В этом режиме pgbadger автоматически создаёт инкрементальный файл в выходном каталоге, поэтому задавать параметр -l не нужно, если вы не хотите изменить путь к этому файлу. Это означает, что вы можете запускать pgbadger в этом режиме каждый день с файлом журнала, который заменяется каждую неделю, и при этом записи журнала не будут учитываться дважды. Для экономии места на диске вы можете использовать параметр командной строки -X/--extra-files, чтобы pgbadger записывал ресурсы CSS и JavaScript в отдельные файлы в выходном каталоге. Тогда эти ресурсы будут подключены с использованием тегов script и link.

В инкрементальном режиме вы также можете указать, сколько недель должно сохраняться в отчёте, воспользовавшись параметром -O/--retention:

/usr/bin/pgbadger --retention 2 -I -q /var/lib/pgpro/ent-18/data/log/postgresql/postgresql.log.1 -O /var/www/pg_reports/

Если запуск pg_dump запланирован на 23:00 и 13:00 каждый день, вы можете исключить эти периоды из отчёта следующим образом:

pgbadger --exclude-time "2013-09-.* (23|13):.*" postgresql.log

Это поможет избежать появления операторов COPY, которые выдаёт pg_dump, в верху списка самых медленных запросов. Вы также можете использовать --exclude-appname "pg_dump", чтобы решить эту проблему более простым способом.

Перестроение отчётов

Чтобы обновить все HTML-отчёты после исправления или расширения функциональности отчётов pgbadger, вы можете перестроить инкрементальные отчёты, если двоичный файл данных сохранился. Для этого выполните:

rm /path/to/reports/*.js
rm /path/to/reports/*.css
pgbadger -X -I -O /var/www/pg_reports/ --rebuild 

При этом также будут обновлены все файлы ресурсов (JavaScript и CSS). Добавьте параметр -E/--explode, если он использовался при создании отчётов.

Создание месячных отчётов

По умолчанию в инкрементальном режиме pgbadger создаются только ежедневные и еженедельные отчёты. Чтобы получить месячный накопительный отчёт, нужно отдельно запустить pgbadger с соответствующим параметром. Например, чтобы создать отчёт за август 2021 года, запустите:

pgbadger -X --month-report 2021-08 /var/www/pg_reports/

В результате в представление календаря с инкрементальными отчётами будет добавлена связанная с названием месяца ссылка на этот месячный отчёт. Построение отчёта за месяц можно запускать каждый день, и этот отчёт будут перестраиваться заново. По умолчанию такие отчёты не строятся, так как они могут формироваться слишком долго. Как и при перестроении отчётов, если отчёты создавались с параметром -E/--explode (включающим разбиение отчёта по базам данных), его необходимо указать и при построении месячного отчёта:

pgbadger -E -X --month-report 2021-08 /var/www/pg_reports/ 

Выбор формата файла отчёта

Формат файла отчёта pgbadger определяется расширением файла, переданного параметру -o/--outfile.

Для создания настраиваемых инкрементальных и накопительных отчётов используйте двоичный формат (-o *.bin).

Например, чтобы ежечасно обновлять отчёт pgbadger из ежедневного файла журнала, вы можете каждый час запускать следующие команды:

# Создать файлы инкрементальных данных в двоичном формате
pgbadger --last-parsed .pgbadger_last_state_file -o sunday/hourX.bin /var/lib/pgpro/ent-18/data/log/postgresql-Sun.log
# Создать новый HTML-отчёт из сгенерированного двоичного файла
pgbadger sunday/*.bin

В качестве другого примера предположим, что у вас каждый час создаётся новый файл журнала. Чтобы отчёты перестраивались при каждой ротации журнала, выполните:

pgbadger -o day1/hour01.bin /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-23_10.log
pgbadger -o day1/hour02.bin /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-23_11.log
pgbadger -o day1/hour03.bin /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-23_12.log
...

А чтобы обновлять HTML-отчёт, например, каждый раз после создания нового двоичного файла, просто запустите:

pgbadger -o day1_report.html day1/*.bin

Настройте команды в соответствии с вашими потребностями.

Применяйте формат JSON (-o *.json) для обмена данными с другими языками и для облегчения использования вывода pgbadger другими средствами мониторинга, такими как Cacti или Graphite.

Вы можете использовать и другие форматы вывода, соответствующие вашим потребностям. Например, следующая команда создаст XML-файл сеансов Tsung только для запросов SELECT:

  pgbadger -S -o sessions.tsung --prefix '%t [%p]: user=%u,db=%d ' /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
  

Коды выхода

pgbadger возвращает следующие коды выхода:

  • 0: успешное завершение работы

  • 1: работа прервана из-за ошибки

  • 2: работа была прервана, например с помощью Ctrl+C

  • 3: файл PID уже существует или не может быть создан

  • 4: в командной строке не был указан файл журнала

Параметры #

В этом разделе описываются параметры командной строки pgbadger.

-a минуты
--average минуты #

Указывает длительность интервала (в минутах) для построения графика усреднённых значений для запросов и подключений.

По умолчанию: 5.

-A минуты
--histo-average минуты #

Указывает длительность интервала (в минутах) для построения гистограмм для запросов.

По умолчанию: 60.

-b дата_время
--begin дата_время #

Дата и время или только время начала диапазона анализируемых данных в журналах.

-c сервер
--dbclient сервер #

Обрабатывать только записи, относящиеся к указанному клиентскому компьютеру.

-C
--nocomment #

Удалять из запросов комментарии /* ... */.

-d имя
--dbname имя #

Обрабатывать только записи, относящиеся к указанной базе данных.

-D
--dns-resolv #

Заменять IP-адреса клиентов их DNS-именами.

Предупреждение

Это может значительно замедлить работу pgbadger.

-e дата_время
--end дата_время #

Дата и время или только время конца диапазона анализируемых данных в журналах.

-E
--explode #

Строить отдельные отчёты для разных баз данных. Глобальная информация, не связанная с какой-либо базой данных, добавляется в отчёт по базе данных postgres.

-f тип_журнала
--format тип_журнала #

Указывает тип журнала.

Возможные значения: syslog, syslog2, stderr, jsonlog, csv, pgbouncer, logplex, rds и redshift. Следует использовать, когда pgbadger не может определить формат журнала.

-G
--nograph #

Отключает графики в выводе HTML.

-h
--help #

Вывести подробную информацию о параметрах pbadger и завершиться.

-H путь
--html-outdir путь #

Указывает путь к каталогу, в который будет записываться HTML-отчёт в инкрементальном режиме. Обратите внимание, что двоичные файлы остаются в каталоге, указанном в -O/--outdir.

-i имя
--ident имя #

Имя программы, по которому можно выделить сообщения Postgres Pro в журналах syslog.

По умолчанию: postgres.

-I
--incremental #

Использовать инкрементальный режим, в котором отчёты будут генерироваться по дням в отдельном каталоге, указанном параметром -O/--outdir.

-j число
--jobs число #

Задаёт количество одновременно выполняемых заданий обработки журнала. Журналы csvlog всегда обрабатываются в однопоточном режиме.

По умолчанию: 1.

-J число
--Jobs число #

Указывает количество файлов журнала, которые могут разбираться параллельно.

По умолчанию: 1.

-l имя_файла
--last-parsed имя_файла #

Указывает файл для сохранения последней разобранной строки и её даты в целях обеспечения инкрементальной обработки журналов. Полезно использовать для просмотра ошибок с момента последнего запуска или для получения одного отчёта в день с еженедельной ротацией журнала.

-L имя_файла
--logfile-list имя_файла #

Указывает файл, содержащий список файлов журналов для анализа.

-m размер
--maxlength размер #

Задаёт максимальную длину запроса в отчётах (в символах). Более длинные запросы будут усечены.

По умолчанию: 100000.

-M
--no-multiline #

Отключает составление многострочных операторов. Таким образом отчёты становятся чище, особенно в случае ошибок, когда выводится много лишнего.

-N имя
--appname имя #

Обрабатывать только записи журнала, относящиеся к указанному приложению.

-o имя_файла
--outfile имя_файла #

Указывает имя файла для вывода и определяет формат файла отчёта: out.html, out.txt, out.bin или out.json. Может использоваться несколько раз для получения разных форматов. Для вывода json убедитесь, что установлен Perl-модуль JSON::XS. Если в качестве имени файла указать «-», отчёт будет записан в стандартный вывод.

По умолчанию: out.html, out.txt, out.bin, out.json или out.tsung,

для соответствующего формата вывода.

-O путь
--outdir путь #

Указывает каталог, в который будут записаны выходные файлы.

-p строка
--prefix строка #

Указывает значение настраиваемого параметра log_line_prefix, заданное в файле postgresql.conf. Полезен в случаях, когда вы используете префикс строк, отличный от стандартных префиксов log_line_prefix, например, когда префикс включает дополнительные переменные, такие как IP-адрес клиента или имя приложения. Строка должна содержать спецпоследовательности для указания времени (%t, %m или %n) и процессов (%p или %c).

-P
--no-prettify #

Отключает улучшение визуального представления кода SQL-запросов.

-q
--quiet #

Полностью отключает вывод в stdout, не выводится даже индикатор выполнения.

-Q
--query-numbering #

Добавляет нумерацию запросов в вывод, когда используется ключ --dump-all-queries или --normalized-only.

-r адрес
--remote-host адрес #

Указывает компьютер, на котором выполнится команда cat для удалённого файла; её вывод будет разобран локально.

-R число
--retention число #

Задаёт интервал (в неделях), в течение которого отчёты должны сохраняться в каталоге вывода в инкрементальном режиме. Каталоги предшествующих недель и дней удаляются автоматически.

По умолчанию: 0 (отчёты не удаляются).

-s число
--sample число #

Задаёт количество сохраняемых выборок запросов.

По умолчанию: 3.

-S
--select-only #

Обрабатывать только запросы SELECT.

-t число
--top число #

Указывает количество запросов для хранения/отображения.

По умолчанию: 20.

-T строка
--title строка #

Указывает заголовок страницы отчёта в формате HTML.

-u имя_пользователя
--dbuser имя_пользователя #

Обрабатывать только записи журнала, относящиеся к указанному пользователю.

-U имя_пользователя
--exclude-user имя_пользователя #

Указывает имя пользователя для исключения относящихся к нему записей из отчёта.

-v
--verbose #

Включает подробный режим или режим отладки.

По умолчанию: выкл.

-V
--version #

Вывести версию pgbadger и завершиться.

-w
--watch-mode #

Обрабатывать только ошибки, по аналогии с Logwatch.

-W
--wide-char #

Кодировать HTML-вывод запросов в UTF-8, чтобы избежать сообщений Perl «Wide character in print» (Широкий символ в print).

-x формат
--extension формат #

Задаёт формат вывода. Возможные значения: text, html, bin или json.

По умолчанию: html.

-X
--extra-files #

В инкрементальном режиме записывать ресурсы CSS и JavaScript в каталог вывода как отдельные файлы.

-z команда
--zcat команда #

Задаёт полную команду для запуска программы zcat. Используйте, если zcat, bzcat или unzip находится не в каталоге, включённом в PATH.

-Z +/-XX
--timezone +/-XX #

Задаёт смещение часового пояса от GMT. Используйте для настройки даты/времени в графиках JavaScript. Значение может быть целым числом (например, 2) или числом с плавающей точкой (например, 2.5).

--pie-limit число #

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

--exclude-query регулярное_выражение #

Задаёт регулярное выражение, при совпадении с которым запросы будут исключены из отчёта. Например: «^(VACUUM|COMMIT)». Можно использовать несколько раз.

--exclude-file имя_файла #

Указывает путь к файлу, содержащему все регулярные выражения для исключения соответствующих им запросов из отчёта, по одному выражению в строке.

--include-query регулярное_выражение #

Задаёт регулярное выражение для включения соответствующих ему запросов в отчёт. Можно использовать несколько раз. Например: «(tbl1|tbl2)».

--include-file имя_файла #

Указывает путь к файлу, содержащему все регулярные выражения для включения соответствующих им запросов в отчёт, по одному выражению в строке.

--disable-error #

Отключает формирование отчёта об ошибках.

--disable-hourly #

Отключает формирование почасового отчёта.

--disable-type #

Отключает формирование отчёта о запросах по типам, базам данных и пользователям.

--disable-query #

Отключает формирование отчётов о запросах, например: самых медленных и наиболее частых, по пользователям, базам данных и т. д.

--disable-session #

Отключает формирование отчёта о сеансах.

--disable-connection #

Отключает формирование отчёта о соединениях.

--disable-lock #

Отключает формирование отчёта о блокировках.

--disable-temporary #

Отключает формирование отчёта о временных файлах.

--disable-checkpoint #

Отключает формирование отчётов о контрольных точках/точках перезапуска.

--disable-autovacuum #

Отключает формирование отчёта об автоочистке.

--charset имя #

Указывает набор символов HTML, который будет использоваться.

По умолчанию: utf-8.

--csv-separator char #

Указывает разделитель полей CSV.

По умолчанию: «,».

--exclude-time регулярное_выражение #

Указывает регулярное выражения для исключения из отчёта записей с соответствующей ему меткой времени. Например: «2013-04-12 .*». Можно использовать несколько раз.

--include-time регулярное_выражение #

Указывает регулярное выражение для включения в отчёт записей с соответствующей ему меткой времени. Например: «2013-04-12 .*». Можно использовать несколько раз.

--exclude-db имя #

Указывает имя базы данных для исключения связанных с ней записей журнала из отчёта. Например: «outdated_db». Можно использовать несколько раз.

--exclude-appname имя #

Задаёт имя приложения для исключения связанных с ним записей журнала из отчёта. Например: «pg_dump». Можно использовать многократно.

--exclude-line регулярное_выражение #

Указывает регулярное выражение для исключения из отчёта записей журнала при совпадении со всей строкой. Можно использовать несколько раз.

--exclude-client имя #

Указывает IP-адрес/имя клиента для исключения связанных с ним записей журнала из отчёта. Можно использовать несколько раз.

--anonymize #

Анонимизировать все константы в запросах. Позволяет скрыть конфиденциальные данные.

--noreport #

Отключает формирование отчётов в инкрементальном режиме.

--log-duration #

Связывать записи журнала, сформированные в результате действия параметров log_duration = on и log_statement = all.

--enable-checksum #

Добавить сумму MD5 под каждым запросом.

--journalctl команда #

Указывает команду для генерирования информации, аналогичной той, что содержится в файле журнала Postgres Pro. Обычно это: journalctl -u postgrespro-ent-18.

--pid-dir путь #

Указывает путь к файлу с PID.

По умолчанию: /tmp.

--pid-file имя_файла #

Указывает имя файла с PID для управления параллельным выполнением pgbadger.

По умолчанию: pgbadger.pid.

--rebuild #

Перестроить все HTML-отчёты в каталогах инкрементального вывода, содержащих файлы двоичных данных.

--pgbouncer-only #

Показывать в заголовке только связанные с pgbouncer меню.

--start-monday #

Начинать календарные недели с понедельника (в инкрементальном режиме). По умолчанию они начинаются в воскресенье.

--iso-week-number #

Начинать календарные недели в инкрементальном режиме с понедельника (по умолчанию недели начинаются с воскресенья), с нумерацией недель согласно ISO 8601: от 01 до 53, где первая неделя — это первая неделя года, в которой не менее 4 дней.

--normalized-only #

Только выгрузить все нормализованные запросы в файл out.txt.

--log-timezone +/-XX #

Задаёт смещение часового пояса для пересчёта значений даты/времени, прочитанных из файла журнала, перед анализом. Ненулевое смещение усложняет поиск соответствующих записей в журнале по дате/времени. Значение может быть целым числом (например, 2) или числом с плавающей точкой (например, 2.5).

--prettify-json #

Улучшать визуальное представление JSON.

--month-report ГГГГ-ММ #

Указывает месяц (ГГГГ-ММ), за который нужно построить сводный HTML-отчёт. Для построения отчёта требуются каталоги инкрементального вывода, содержащие все необходимые двоичные данные.

--day-report ГГГГ-ММ-ДД #

Указывает день (ГГГГ-ММ-ДД) для создания HTML-отчёта. Для построения отчёта требуются каталоги инкрементального вывода, содержащие все необходимые двоичные данные.

--noexplain #

Отключает обработку строк журнала, сформированных механизмом auto_explain.

--command команда #

Задаёт команду, от которой будет получаться содержимое журнала через stdin. pgbadger откроет канал для получения её вывода и будет анализировать выводимые ею записи.

--no-week #

Не строить еженедельные запросы в инкрементальном режиме. Это полезно, если такие отчёты строятся слишком долго.

--explain-url URL #

Позволяет переопределить URL визуализатора вывода EXPLAIN ANALYZE.

По умолчанию: http://explain.depesz.com/

--tempdir путь #

Указывает каталог для временных файлов.

По умолчанию: File::Spec->tmpdir() || '/tmp'.

--no-process-info #

Отключает смену названия процесса pgbadger на другое, помогающее идентифицировать этот процесс. Полезно в системах, в которых не поддерживается изменение названия процесса.

--dump-all-queries #

Выгрузить все запросы, найденные в файле журнала, в текстовый файл, подставляя значения привязываемых параметров в соответствующие позиции в запросах.

--keep-comments #

Сохранять комментарии в нормализованных запросах. Это позволяет различать одинаковые нормализованные запросы.

--no-progressbar #

Отключает вывод индикатора выполнения.

--dump-raw-csv #

Разобрать журнал и выгрузить информацию в формате CSV без дальнейшей обработки и создания отчёта.

--include-pid PID #

Сообщать только о событиях, связанных с PID сеанса (%p). Можно использовать несколько раз.

--include-session ID #

Сообщать только о событиях, связанных с ID сеанса (%c). Можно использовать несколько раз.

--histogram-query VAL #

Использовать пользовательские входящие для гистограммы времени запроса. Входящие по умолчанию в миллисекундах: 0, 1, 5, 10, 25, 50, 100, 500, 1000, 10000.

--histogram-session VAL #

Использовать пользовательские входящие для гистограммы времени сеанса. Входящие по умолчанию в миллисекундах: 0, 500, 1000, 30000, 60000, 600000, 1800000, 3600000, 28800000.

Параметры подключения к удалённому журналу #

pgbadger может анализировать удалённые файлы журналов, получаемые через SSH-соединение без пароля. IP-адрес или имя целевого компьютера задаётся в параметре -r/--remote-host. Другие свойства SSH-подключения определяются следующими параметрами:

--ssh-program ssh

Указывает путь к используемому SSH-клиенту.

По умолчанию: ssh.

--ssh-port порт

Указывает порт SSH для подключения.

По умолчанию: 22.

--ssh-user имя_пользователя

Указывает имя пользователя для подключения.

По умолчанию: имя пользователя, запускающего pgbadger.

--ssh-identity имя_файла

Указывает путь к файлу идентификации.

--ssh-timeout секунды

Задаёт тайм-аут в секундах на случай сбоя SSH-соединения.

По умолчанию: 10.

--ssh-option параметры

Задаёт список параметров для SSH-соединения. Следующие параметры используются всегда:

-o ConnectTimeout=$ssh_timeout -o PreferredAuthentications=hostbased,publickey

-o PreferredAuthentications=hostbased,publickey

Автор

Жиль Даролд

pgbadger

pgbadger — rapidly analyze Postgres Pro logs, producing detailed reports and graphs

Synopsis

pgbadger [connection-option...] [option...] [logfile...]

Description

pgbadger is a Postgres Pro/PostgreSQL log analyzer, which rapidly provides detailed reports based on your log files. pgbadger is provided with Postgres Pro as a standalone Perl script.

logfile can be a single log file, a list of files or a shell command that returns a list of files. To get log content from the standard input, pass - as logfile.

pgbadger can parse huge log files and compressed files. It can autodetect your log file format (syslog, stderr, csvlog or jsonlog) if the file is long enough. Supported compressed formats are gzip, bzip2, lz4, xz, zip and zstd. For the xz format, you must have an xz version higher than 5.05, which supports the --robot option. For pgbadger to determine the uncompressed file size for the lz4 format, the file must be compressed with the --content-size option.

pgbadger supports any format of log-line prefixes that can be specified through the log_line_prefix configuration setting of your postgresql.conf configuration file, provided that at least %t and %p are specified.

pgbouncer log files can also be parsed.

To speed up log parsing, you can use any of these multiprocessing modes: one core per log file and multiple cores per file. These modes can be combined.

pgbadger can also parse remote log files fetched using a passwordless SSH connection. This mode can be used with compressed files and even supports multiprocessing with multiple cores per file.

Examples of reports can be found at https://pgbadger.darold.net/#reports.

Limitations #

pgbadger currently has the following limitations:

  • Multiprocessing is not supported for compressed log files and CSV files, as well as on Windows.

  • CSV format of log files cannot be parsed remotely.

  • csvlog logs cannot be passed from the standard input.

Setup and Configuring #

pgbadger is provided with Postgres Pro Enterprise as a separate pre-built package pgbadger (for the detailed installation instructions, see Chapter 17). Once you have pgbadger installed, complete the setup described in sections below.

[Optional] Set up Parsing Specific Log Formats

If you plan to parse CSV log files, install Text::CSV_XS Perl module.

[Optional] Set up Export of Statistics

If you want to export statistics as a JSON file, install JSON::XS Perl module:

To install this optional module:

  • On a Debian-based system, run:

    sudo apt-get install libjson-xs-perl
    

  • On an RPM system, run:

    sudo yum install perl-JSON-XS
    

[Optional] Set up Parsing Compressed Log Files

By default, pgbadger autodetects the compressed log file format from the file extension and uses decompression utilities accordingly:

  • zcat for gz

  • bzcat for bz2

  • lz4cat for lz4

  • zstdcat for zst

  • unzip or xz for zip or xz

If the needed utility is outside of your PATH directories, use the --zcat command-line option to specify the path to the decompression utility. For example:

--zcat="/usr/local/bin/gunzip -c" or --zcat="/usr/local/bin/bzip2 -dc"
--zcat="C:\tools\unzip -p"

Note

With the default autodetection of the compressed file format, you can mix gz, bz2, lz4, xz, zip and zstd log files. Once you specified a custom value of --zcat, mixing compressed files of different formats is longer possible.

Configure Your Postgres Pro Server

Set the values of certain configuration parameters in your postgresql.conf:

  • Set up logging SQL queries.

    To enable SQL query logging and have the query statistics include actual query strings, set

    log_min_duration_statement = 0
    

    On a busy server you may want to increase this value to only log queries with a longer duration.

    If you just want to report the duration and number of queries and do not want details of queries, set log_min_duration_statement to -1, which disables logging statement durations, and enable log_duration.

    Enabling log_min_duration_statement will add reports about slowest queries and queries that took the most time. Note that if you set log_statement to all, the setting of log_min_duration_statement will have no effect.

    Warning

    Avoid setting log_min_duration_statement to a non-positive value together with enabling log_duration and log_statement as this will result in wrong counter values and drastically increase the size of your log. Always prefer setting log_min_duration_statement.

  • Set the log line prefix string in log_line_prefix.

    It must at least include a time escape sequence (%t, %m or %n) and the process-related escape sequence (%p or %c). For example, for stderr logs, the setting must be at least

    log_line_prefix = '%t [%p]: '
    

    The log line prefix could also specify the user, database name, application name and client IP address. For example,

    for stderr logs:

    log_line_prefix = '%t [%p]: user=%u,db=%d,app=%a,client=%h '
    

    or

    log_line_prefix = '%t [%p]: db=%d,user=%u,app=%a,client=%h '
    

    and for syslog logs:

    log_line_prefix = 'user=%u,db=%d,app=%a,client=%h '
    

    or

    log_line_prefix = 'db=%d,user=%u,app=%a,client=%h '
    

  • To get more information from your log files, set certain configuration parameters as follows:

    log_checkpoints = on
    log_connections = on
    log_disconnections = on
    log_lock_waits = on
    log_temp_files = 0
    log_autovacuum_min_duration = 0
    log_error_verbosity = default
    

    To benefit from these settings, do not enable log_statement as pgbadger does not parse the corresponding log format.

  • Set the language in which messages are displayed; messages must be in English with or without locale support:

    lc_messages='C'
    

    or

    lc_messages='en_US.UTF-8'
    

    Locales for other languages, such as ru_RU.utf8, are not supported.

Usage #

The following are simple examples to illustrate miscellaneous pgbadger usage details.

pgbadger /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger /var/lib/pgpro/ent-18/data/log/postgres.log.2.gz /var/lib/pgpro/ent-18/data/log/postgres.log.1.gz /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger /var/lib/pgpro/ent-18/data/log/postgresql/postgresql-2022-01-*
pgbadger --exclude-query="^(COPY|COMMIT)" /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger -b "2022-01-25 10:56:11" -e "2022-01-25 10:59:11" /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-25-0000.log 
cat /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log | pgbadger -
# Log line prefix with stderr log output
pgbadger --prefix '%t [%p]: user=%u,db=%d,client=%h' /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21*
pgbadger --prefix '%m %u@%d %p %r %a : ' /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21-0000.log
# Log line prefix with syslog log output
pgbadger --prefix 'user=%u,db=%d,client=%h,appname=%a' /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21*
# Use 8 CPUs to parse 10GB file faster
pgbadger -j 8 /var/lib/pgpro/ent-18/data/log/postgresql-2022-08-21-0000.log
# Use a cron job to report errors weekly
30 23 * * 1 /usr/bin/pgbadger -q -w /var/lib/pgpro/ent-18/data/log/postgresql-2022-01*.log -o /var/www/pg_reports/pg_errors.html

Specifying Remote Log Files

Specify remote log files to parse using a URI. Supported protocols are HTTP[S] and [S]FTP. The curl command will be used to download the file, and the file will be parsed during download. The SSH protocol is also supported and will use the ssh command to get log files, as when the --remote-host option is used.

Use these URI notations for the remote log file:

pgbadger http://172.12.110.1//var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
pgbadger ftp://username@172.12.110.14/postgresql-2022-01-14_000000.log
pgbadger ssh://username@172.12.110.14:2222//var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log*

You can parse a local Postgres Pro log and a remote pgbouncer log file together:

pgbadger /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log ssh://username@172.12.110.14/pgbouncer.log  

Parallel Processing

To enable parallel processing, specify the -j N option, where N is the number of cores to use.

Parallel processing in pgbadger follows the algorithm below:

For each log file
  chunk size = int(file size / N)
  look at start/end offsets of these chunks
  fork N processes and seek to the start offset of each chunk
    each process will terminate when the parser reaches the end offset of its chunk
    each process writes stats into a binary temporary file
  wait for all child processes to terminate
All binary temporary files generated will then be read and loaded into
memory to build the html output.

With this method, at start/end of chunks pgbadger may truncate or omit a maximum of N queries per log file, which is an insignificant gap if you have millions of queries in your log file. The chance that the query that you were looking for is lost is near zero, so this gap can be considered suitable. Most of the time the query is counted twice, but truncated.

When you have many small log files and many CPUs, it is faster to dedicate one core to one log file at a time. To enable this behavior, specify the -J N option instead. Using this method, you can be sure not to lose any queries in the reports. With 200 log files of 10 MB each, the -J option starts being really efficient with 8 cores.

Here is a benchmark done on a server with 8 CPUs and a single file of 9.5 GB.

 Option |  1 CPU  | 2 CPU | 4 CPU | 8 CPU
--------+---------+-------+-------+------
   -j   | 1h41m18 | 50m25 | 25m39 | 15m58
   -J   | 1h41m18 | 54m28 | 41m16 | 34m45

With 200 log files of 10 MB each, which is 2 GB in total, the results are slightly different:

 Option | 1 CPU | 2 CPU | 4 CPU | 8 CPU
--------+-------+-------+-------+------
   -j   | 20m15 |  9m56 |  5m20 | 4m20
   -J   | 20m15 |  9m49 |  5m00 | 2m40

So it is recommended to use the -j option unless you have hundreds of small log files and can use at least 8 CPUs.

Important

During parallel parsing, pgbadger generates a lot of temporary files named tmp_pgbadgerXXXX.bin in the /tmp directory and removes them at the end.

Building Incremental Reports

The following sample cron job builds a report every week with the incremental behavior assuming that your log file and HTML report are also rotated every week:

0 4 * * 1 /usr/bin/pgbadger -q `find /var/lib/pgpro/ent-18/data/log/ -mtime -7 -name "postgresql.log*"` -o /var/www/pg_reports/pg_errors-`date +\%F`.html -l /var/reports/pgbadger_incremental_file.dat

But better turn on pgbadger's automatic building incremental reports by specifyng the -I/--incremental option. In this mode, pgbadger builds one report per day and a cumulative report per week. The output is first built in the binary format and saved to the output directory, specified by the -O/--outdir option, and then daily and weekly reports are built in the HTML format with the main index file. The main index file shows a dropdown menu per week with a link to the week's report and links to daily reports for that week. For example, run pgbadger as follows with the file rotated daily:

0 4 * * * /usr/bin/pgbadger -I -q /var/lib/pgpro/ent-18/data/log/postgresql/postgresql.log.1 -O /var/www/pg_reports/

You will have all daily and weekly reports. In this mode pgbadger will automatically create an incremental file in the output directory, so you do not have to use the -l option unless you want to change the path of that file. This means that you can run pgbadger in this mode every day on a log file rotated every week and it will not count the log entries twice. To save disk space, you may want to use the -X/--extra-files command-line option to force pgbadger to write CSS and JavaScript files to the output directory as separate files. The resources will then be loaded using script and link tags.

In the incremental mode, you can also specify the number of weeks to keep in the report by using the -O/--retention option:

/usr/bin/pgbadger --retention 2 -I -q /var/lib/pgpro/ent-18/data/log/postgresql/postgresql.log.1 -O /var/www/pg_reports/

If pg_dump is scheduled to run at 23:00 and 13:00 every day, you can exclude these periods from the report as follows:

pgbadger --exclude-time "2013-09-.* (23|13):.*" postgresql.log

This will help avoid having COPY statements generated by pg_dump on top of the list of slowest queries. Alternatively, you can use --exclude-appname "pg_dump" to solve this problem in a simpler way.

Rebuilding Reports

To update all HTML reports after fixing a pgbadger report or adding a new feature to it, you can rebuild incremental reports. To rebuild all reports in the case a binary file is still available, run:

rm /path/to/reports/*.js
rm /path/to/reports/*.css
pgbadger -X -I -O /var/www/pg_reports/ --rebuild 

This will also update all the resource files (JavaScript and CSS). Use the -E/--explode option if the reports were built with this option.

Building Monthly Reports

By default, in the incremental mode pgbadger only computes daily and weekly reports. To have monthly cumulative reports, you will need to use a separate command to specify the report to build. For example, to build a report for August 2021, run:

pgbadger -X --month-report 2021-08 /var/www/pg_reports/

This will add a link to the month name to the calendar view of incremental reports to look at the monthly report. The report for a current month can be run every day, and it is entirely rebuilt each time. The monthly report is not built by default because it could take too long. Like when rebuilding reports, if reports were built with the per-database option (-E/--explode), it must be used to build the monthly report:

pgbadger -E -X --month-report 2021-08 /var/www/pg_reports/ 

Choosing the Report File Format

The pgbadger report file format is determined by the extension of the file passed to the -o/--outfile option.

Use the binary format (-o *.bin) to create custom incremental and cumulative reports.

For example, to refresh a pgbadger report every hour from a daily log file, you can run the following commands every hour:

# Generate incremental data files in the binary format
pgbadger --last-parsed .pgbadger_last_state_file -o sunday/hourX.bin /var/lib/pgpro/ent-18/data/log/postgresql-Sun.log
# Build a fresh HTML report from the generated binary file
pgbadger sunday/*.bin

For another example, assume that you generate one log file per hour. To have reports rebuilt each time the log file is rotated, run:

pgbadger -o day1/hour01.bin /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-23_10.log
pgbadger -o day1/hour02.bin /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-23_11.log
pgbadger -o day1/hour03.bin /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-23_12.log
...

And to refresh the HTML report, for example, each time after a new binary file is generated, just run:

pgbadger -o day1_report.html day1/*.bin

Adjust the commands to your particular needs.

Use the JSON format (-o *.json) to share data with other languages and to facilitate integration of pgbadger output with other monitoring tools, such as Cacti or Graphite.

Select other output formats to meet your particular needs. For example, this command will generate Tsung sessions XML file for SELECT queries only:

  pgbadger -S -o sessions.tsung --prefix '%t [%p]: user=%u,db=%d ' /var/lib/pgpro/ent-18/data/log/postgresql-2022-01-14_000000.log
  

Return Codes

pgbadger return codes depend on how it terminated as follows:

  • 0: was a success

  • 1: died on error

  • 2: has been interrupted using Ctrl+C, for example

  • 3: the PID file already exists or cannot be created

  • 4: no log file was specified on the command line

Options #

This section describes pgbadger command-line options.

-a minutes
--average minutes #

Specifies the number of minutes for which to build average graphs of queries and connections.

Default: 5.

-A minutes
--histo-average minutes #

Specifies the number of minutes for which to build histogram graphs of queries.

Default: 60.

-b datetime
--begin datetime #

Timestamp or time that specifies the start date/time for the data to be parsed in logs.

-c host
--dbclient host #

Only report on log entries for the specified client host.

-C
--nocomment #

Remove /* ... */ comments from queries.

-d name
--dbname name #

Only report on log entries for the specified database.

-D
--dns-resolv #

Replace client IP addresses with their DNS names.

Warning

This can considerably slow down pgbadger.

-e datetime
--end datetime #

Timestamp or time that specifies the end date/time for the data to be parsed in logs.

-E
--explode #

Build one report per each database. Global information not related to any database gets added to the postgres database report.

-f logtype
--format logtype #

Specifies the log type.

Possible values: syslog, syslog2, stderr, jsonlog, csv, pgbouncer, logplex, rds and redshift. Use when pgbadger cannot detect the log format.

-G
--nograph #

Disables graphs in HTML output.

-h
--help #

Show detailed information about pbadger options and exit.

-H path
--html-outdir path #

Specifies the path to the directory where the HTML report must be written in the incremental mode. Note that binary files remain in the directory specified by -O/--outdir.

-i name
--ident name #

Specifies the program name used to identify Postgres Pro messages in syslog logs.

Default: postgres.

-I
--incremental #

Use the incremental mode, where reports will be generated by days in a separate directory specified by the -O/--outdir option.

-j number
--jobs number #

Specifies the number of jobs to run at the same time. When working with csvlog logs, pgbadger always runs as single job.

Default: 1.

-J number
--Jobs number #

Specifies the number of log files to parse in parallel.

Default: 1.

-l filename
--last-parsed filename #

Specifies the file where the last datetime and line parsed are registered to allow incremental log parsing. Useful to watch errors since the last run or to get one report per day with the log rotated weekly.

-L filename
--logfile-list filename #

Specifies the file containing the list of log files to parse.

-m size
--maxlength size #

Specifies the maximum length of a query in reports. Longer queries will be truncated.

Default: 100000.

-M
--no-multiline #

Turns off collecting multiline statements to avoid reporting excessive information, especially on errors that generate a huge report.

-N name
--appname name #

Only report on log entries for the specified application.

-o filename
--outfile filename #

Specifies the filename for the output and determines the report file format: out.html, out.txt, out.bin or out.json. Can be used multiple times to output several formats. For the json output, ensure that the Perl module JSON::XS is installed. To dump the output to stdout, use the value of - as filename.

Default: out.html, out.txt, out.bin, out.json or out.tsung,

for the respective output format.

-O path
--outdir path #

Specifies the directory where out files must be saved.

-p string
--prefix string #

Specifies the value of your custom log_line_prefix string, as defined in your postgresql.conf. Only use if your log line prefix is different from the standard log_line_prefix strings, for example, if your prefix includes additional variables, such as client IP or application name. The string must contain escape sequences for time (%t, %m or %n) and processes (%p or %c).

-P
--no-prettify #

Disables SQL query code prettifier.

-q
--quiet #

Disables printing anything to stdout, even the progress bar.

-Q
--query-numbering #

Add numbering of queries to the output when used together with --dump-all-queries or --normalized-only.

-r address
--remote-host address #

Specifies the host to execute the cat command on a remote log file to parse the file locally.

-R number
--retention number #

Specifies the number of weeks for which to keep reports in the output directory in the incremental mode. The directories for older weeks and days are automatically removed.

Default: 0 (no reports are removed).

-s number
--sample number #

Specifies the number of query samples to store.

Default: 3.

-S
--select-only #

Only report on SELECT queries.

-t number
--top number #

Specifies the number of queries to store/display.

Default: 20.

-T string
--title string #

Specifies the title of the HTML report page.

-u username
--dbuser username #

Only report on log entries for the specified username.

-U username
--exclude-user username #

Specifies the username to exclude log entries for from the report. Can be used multiple times.

-v
--verbose #

Enables the verbose or debug mode.

Default: off.

-V
--version #

Show pgbadger version and exit.

-w
--watch-mode #

Only report errors, just like Logwatch can do.

-W
--wide-char #

Encode HTML output of queries in UTF8 to avoid Perl messages Wide character in print.

-x format
--extension format #

Specfies the output format. Possible values: text, html, bin or json.

Default: html.

-X
--extra-files #

In the incremental mode, write CSS and JavaScript resources to the output directory as separate files.

-z command
--zcat command #

Specifies the full command to run the zcat program. Use if zcat, bzcat or unzip is outside of your PATH directories.

-Z +/-XX
--timezone +/-XX #

Specifies the number of hours from GMT for the timezone. Use to adjust date/time in JavaScript graphs. The value can be an integer (e.g., 2), or a float, (e.g., 2.5).

--pie-limit number #

Specifies the number such that instead of lower pie data the sum will be shown.

--exclude-query regexp #

Specifies the regular expression such that matching queries will be excluded from the report. For example: ^(VACUUM|COMMIT). Can be used multiple times.

--exclude-file filename #

Specifies the path to the file that contains each regular expression to use to exclude matching queries from the report, one expression per line.

--include-query regexp #

Specifies the regular expression such that only matching queries will be included in the report. Can be used multiple times. For example: (tbl1|tbl2).

--include-file filename #

Specifies the path to the file that contains each regular expression to use to include matching queries in the report, one expression per line.

--disable-error #

Turns off generation of an error report.

--disable-hourly #

Turns off generation of an hourly report.

--disable-type #

Turns off generation of a report on queries by type, database and user.

--disable-query #

Turns off generation of query reports, such as slowest or most frequent queries, queries by users, by database and so on.

--disable-session #

Turns off generation of a session report.

--disable-connection #

Turns off generation of a connection report.

--disable-lock #

Turns off generation of a lock report.

--disable-temporary #

Turns off generation of a report on temporary files.

--disable-checkpoint #

Turns off generation of checkpoint/restartpoint reports.

--disable-autovacuum #

Turns off generation of an autovacuum report.

--charset name #

Specifies the HTML charset to be used.

Default: utf-8.

--csv-separator char #

Specifies the CSV field separator.

Default: ,.

--exclude-time regexp #

Specifies the regular expression such that log entries for any matching timestamp will be excluded from the report. For example: 2013-04-12 .*. Can be used multiple times.

--include-time regexp #

Specifies the regular expression such that log entries for any matching timestamp will be included in the report. For example: 2013-04-12 .*. Can be used multiple times.

--exclude-db name #

Specifies the name of the database to exclude related log entries from the report. For example: outdated_db. Can be used multiple times.

--exclude-appname name #

Specifies the name of the application to exclude related log entries from the report. For example: pg_dump. Can be used multiple time.

--exclude-line regexp #

Specifies the regular expression such that any matching log entry will be excluded from the report. Can be used multiple times.

--exclude-client name #

Specifies the client IP/name to exclude related log entries from the report. Can be used multiple times.

--anonymize #

Obscure all literals in queries. Useful to hide confidential data.

--noreport #

Prevents generation of reports in the incremental mode.

--log-duration #

Associate log entries generated by log_duration = on and log_statement = all.

--enable-checksum #

Add the MD5 sum under each query report.

--journalctl command #

Specifies the command to produce the information similar to what the Postgres Pro log file contains. Usually, like this: journalctl -u postgrespro-ent-18.

--pid-dir path #

Specifies the path to store the PID file.

Default: /tmp.

--pid-file filename #

Specifies the name of the PID file to manage concurrent execution of pgbadger.

Default: pgbadger.pid.

--rebuild #

Rebuild all HTML reports in incremental output directories that contain binary data files.

--pgbouncer-only #

Only show pgbouncer-related menus in the header.

--start-monday #

In the incremental mode, start calendar weeks on Monday. By default, they start on Sunday.

--iso-week-number #

In the incremental mode, start calendar weeks on Monday (by default, they start on Sunday) with ISO 8601 week numbering: 01 to 53, where week 1 is the first week of a year that has at least 4 days.

--normalized-only #

Only dump all normalized queries to out.txt.

--log-timezone +/-XX #

Specifies the number of hours from GMT for the timezone to adjust date/time read from the log file before parsing. The use of this option makes log search with date/time more complicated. The value can be an integer (e.g., 2), or a float, (e.g., 2.5).

--prettify-json #

Prettify JSON output.

--month-report YYYY-MM #

Specifies the month (YYYY-MM) to create a cumulative HTML report for. Requires incremental output directories to be set and all the necessary binary data files available.

--day-report YYYY-MM-DD #

Specifies the day (YYYY-MM-DD) to create an HTML report for. Requires incremental output directories to be set and all the necessary binary data files available.

--noexplain #

Avoid processing log lines generated by auto_explain.

--command cmd #

Specifies the command to run to retrieve log entries on stdin. pgbadger will open a pipe to this command and parse log entries that it generates.

--no-week #

Avoid building weekly reports in the incremental mode. Use if building weekly reports takes too long.

--explain-url URL #

Specifes the URL to override the URL of the graphical explain tool.

Default: http://explain.depesz.com/

--tempdir path #

Specifies the directory for temporary files.

Default: File::Spec->tmpdir() || '/tmp'.

--no-process-info #

Disables changing the pgbadger process title to help identify this process. Useful for systems where changing process titles is not supported.

--dump-all-queries #

Dump all queries found in the log file to a text file, replacing bind parameters in the queries at their respective placeholder positions.

--keep-comments #

Retains comments in normalized queries. Useful to distinguish between same normalized queries.

--no-progressbar #

Disables displaying the progress bar.

--dump-raw-csv #

Parse the log and dump the information into CSV format. No further processing is done, no report.

--include-pid PID #

Only report events related to the session PID (%p). Can be used multiple times.

--include-session ID #

Only report events related to the session ID (%c). Can be used multiple times.

--histogram-query VAL #

Use custom inbound for query time histogram. Default inbound in milliseconds: 0,1,5,10,25,50,100,500,1000,10000.

--histogram-session VAL #

Use custom inbound for session time histogram. Default inbound in milliseconds: 0,500,1000,30000,60000,600000,1800000,3600000,28800000.

Remote Log Connection Options #

pgbadger can parse a remote log file fetched using passwordless SSH connection. Use the -r/--remote-host option to set the IP address or name of the target host. More options to define SSH connection parameters are as follows:

--ssh-program ssh

Specifies the path to the SSH program to use.

Default: ssh.

--ssh-port port

Specifies the SSH port for the connection.

Default: 22.

--ssh-user username

Specifies the username for the connection.

Default: user running pgbadger.

--ssh-identity filename

Specifies the path to the identity file.

--ssh-timeout seconds

Specifies the timeout in seconds in case of the SSH connection failure.

Default: 10.

--ssh-option options

Specifies the list of options to define SSH connection parameters. The following options are always used:

-o ConnectTimeout=$ssh_timeout -o PreferredAuthentications=hostbased,publickey

-o PreferredAuthentications=hostbased,publickey

Author

Gilles Darold

FAQ