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, настройте его как описано далее.
Подготовка для обработки определённых форматов журнала (необязательно)
Если вы планируете анализировать файлы журналов 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 для
gzbzcat для
bz2lz4cat для
lz4zstdcat для
zstunzip или 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-12/data/log/postgresql-2022-01-14_000000.log pgbadger /var/lib/pgpro/ent-12/data/log/postgres.log.2.gz /var/lib/pgpro/ent-12/data/log/postgres.log.1.gz /var/lib/pgpro/ent-12/data/log/postgresql-2022-01-14_000000.log pgbadger /var/lib/pgpro/ent-12/data/log/postgresql/postgresql-2022-01-* pgbadger --exclude-query="^(COPY|COMMIT)" /var/lib/pgpro/ent-12/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-12/data/log/postgresql-2022-01-25-0000.log cat /var/lib/pgpro/ent-12/data/log/postgresql-2022-01-14_000000.log | pgbadger - # Префикс строк журнала, выводимого в stderr pgbadger --prefix '%t [%p]: user=%u,db=%d,client=%h' /var/lib/pgpro/ent-12/data/log/postgresql-2022-08-21* pgbadger --prefix '%m %u@%d %p %r %a : ' /var/lib/pgpro/ent-12/data/log/postgresql-2022-08-21-0000.log # Префикс строк журнала, выводимого в syslog pgbadger --prefix 'user=%u,db=%d,client=%h,appname=%a' /var/lib/pgpro/ent-12/data/log/postgresql-2022-08-21* # Использовать 8 ядер для ускорения обработки 10-гигабайтного файла pgbadger -j 8 /var/lib/pgpro/ent-12/data/log/postgresql-2022-08-21-0000.log # Задание cron, которое еженедельно формирует отчёт об ошибке 30 23 * * 1 /usr/bin/pgbadger -q -w /var/lib/pgpro/ent-12/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-12/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-12/data/log/postgresql-2022-01-14_000000.log*
Также возможно обрабатывать одновременно и локальные, и удалённые файлы журналов Postgres Pro (в том числе, журнал pgbouncer):
pgbadger /var/lib/pgpro/ent-12/data/log/postgresql-2022-01-14_000000.log ssh://username@172.12.110.14/pgbouncer.log
Параллельная обработка
Чтобы включить параллельную обработку, укажите параметр -j , где NN — количество используемых ядер.
Параллельная обработка в pgbadger выполняется по следующему алгоритму:
Для каждого файла журнала
размер порции = int(размер файла / N)
определить начальное/конечное смещение этих порций
породить N процессов и искать начальное смещение каждого фрагмента
завершать каждый процесс разбора по достижении конечного смещения его фрагмента
записать статистику, собранную процессом, во временный бинарный файл
дождаться завершения всех дочерних процессов
Затем все сгенерированные бинарные временные файлы считываются и загружаются в
память для формирования выходного html.Когда применяется этот метод, pgbadger может усечь или пропустить в начале/конце порций максимум N запросов на файл журнала, что вряд ли имеет значение, если в вашем файле журнала миллионы запросов. Вероятность того, что потеряется именно интересующий вас запрос, близка к нулю, так что потерю такого объёма можно считать приемлемой. В большинстве случаев запрос учитывается дважды, но в усечённом виде.
Если у вас много небольших файлов журналов и много ядер, для ускорения лучше выделить одно ядро на один файл журнала. Чтобы включить такое поведение, укажите параметр -J . Таким образом, вы можете быть уверены, что не потеряете ни одного запроса в отчётах. Например, если обрабатывать 200 файлов по 10 Мбайт каждый, параметр N-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-12/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-12/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-12/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-12/data/log/postgresql-Sun.log # Создать новый HTML-отчёт из сгенерированного двоичного файла pgbadger sunday/*.bin
В качестве другого примера предположим, что у вас каждый час создаётся новый файл журнала. Чтобы отчёты перестраивались при каждой ротации журнала, выполните:
pgbadger -o day1/hour01.bin /var/lib/pgpro/ent-12/data/log/postgresql-2022-01-23_10.log pgbadger -o day1/hour02.bin /var/lib/pgpro/ent-12/data/log/postgresql-2022-01-23_11.log pgbadger -o day1/hour03.bin /var/lib/pgpro/ent-12/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-12/data/log/postgresql-2022-01-14_000000.log
Параметры
В этом разделе описываются параметры командной строки 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числоОпределяет, сколько файлов будет разбираться одновременно. Журналы csvlog обрабатываются по одному.
По умолчанию: 1.
-lимя_файла--last-parsedимя_файлаУказывает файл для сохранения последней разобранной строки и её даты в целях обеспечения инкрементальной обработки журналов. Полезно использовать для просмотра ошибок с момента последнего запуска или для получения одного отчёта в день с еженедельной ротацией журнала.
-Lимя_файла--logfile-listимя_файлаУказывает файл, содержащий список файлов журналов для анализа.
-mразмер--maxlengthразмерЗадаёт максимальную длину запроса в отчётах (в символах). Более длинные запросы будут усечены.
По умолчанию: 100000.
-M--no-multilineОтключает составление многострочных операторов. Таким образом отчёты становятся чище, особенно в случае ошибок, когда выводится много лишнего.
-Nимя--appnameимяОбрабатывать только записи журнала, относящиеся к указанному приложению.
-oимя_файла--outfileимя_файлаУказывает имя файла для вывода и определяет формат файла отчёта. Может использоваться несколько раз для получения разных форматов. Для вывода
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-адрес клиента или имя приложения.-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илиtsung.По умолчанию:
html.-X--extra-filesВ инкрементальном режиме записывать ресурсы CSS и JavaScript в каталог вывода как отдельные файлы.
-zкоманда--zcatкомандаЗадаёт полную команду для запуска программы zcat. Используйте, если zcat, bzcat или unzip находится не в каталоге, включённом в
PATH.-Z+/-XX--timezone+/-XXЗадаёт смещение часового пояса от GMT. Используйте для настройки даты/времени в графиках JavaScript.
--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-separatorcharУказывает разделитель полей 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-12.--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Задаёт смещение часового пояса для пересчёта значений даты/времени, прочитанных из файла журнала, перед анализом. Ненулевое смещение усложняет поиск соответствующих записей в журнале по дате/времени.
--prettify-jsonУлучшать визуальное представление JSON.
--month-reportГГГГ-ММУказывает месяц (ГГГГ-ММ), за который нужно построить сводный HTML-отчёт. Для построения отчёта требуются каталоги инкрементального вывода, содержащие все необходимые двоичные данные.
--day-reportГГГГ-ММ-ДДУказывает день (ГГГГ-ММ-ДД) для создания HTML-отчёта. Для построения отчёта требуются каталоги инкрементального вывода, содержащие все необходимые двоичные данные.
--noexplainОтключает обработку строк журнала, сформированных механизмом auto_explain.
--commandкомандаЗадаёт команду, от которой будет получаться содержимое журнала через stdin. pgbadger откроет канал для получения её вывода и будет анализировать выводимые ею записи.
--no-weekНе строить еженедельные запросы в инкрементальном режиме. Это полезно, если такие отчёты строятся слишком долго.
--explain-urlURLПозволяет переопределить URL визуализатора вывода EXPLAIN ANALYZE.
По умолчанию:
http://explain.depesz.com/?is_public=0&is_anon=0&plan=--tempdirпутьУказывает каталог для временных файлов.
По умолчанию:
File::Spec->tmpdir() || '/tmp'.--no-process-infoОтключает смену названия процесса pgbadger на другое, помогающее идентифицировать этот процесс. Полезно в системах, в которых не поддерживается изменение названия процесса.
--dump-all-queriesВыгрузить все запросы, найденные в файле журнала, в текстовый файл, подставляя значения привязываемых параметров в соответствующие позиции в запросах.
--keep-commentsСохранять комментарии в нормализованных запросах. Это позволяет различать одинаковые нормализованные запросы.
--no-progressbarОтключает вывод индикатора выполнения.
Параметры подключения к удалённому журналу
pgbadger может анализировать удалённые файлы журналов, получаемые через SSH-соединение без пароля. IP-адрес или имя целевого компьютера задаётся в параметре -r/--remote-host. Другие свойства SSH-подключения определяются следующими параметрами:
--ssh-programsshУказывает путь к используемому 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
Автор
Жиль Даролд <gilles@darold.net>
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
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
gzbzcat for
bz2lz4cat for
lz4zstdcat for
zstunzip or xz for
ziporxz
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_statementwill add reports about slowest queries and queries that took the most time. Note that if you set log_statement toall, the setting oflog_min_duration_statementwill have no effect.Warning
Avoid setting
log_min_duration_statementto a non-positive value together with enablinglog_durationandlog_statementas this will result in wrong counter values and drastically increase the size of your log. Always prefer settinglog_min_duration_statement.Set the log line prefix string in log_line_prefix.
It must at least include a time escape sequence (
%t,%mor%n) and the process-related escape sequence (%por%c). For example, for stderr logs, the setting must be at leastlog_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-12/data/log/postgresql-2022-01-14_000000.log pgbadger /var/lib/pgpro/ent-12/data/log/postgres.log.2.gz /var/lib/pgpro/ent-12/data/log/postgres.log.1.gz /var/lib/pgpro/ent-12/data/log/postgresql-2022-01-14_000000.log pgbadger /var/lib/pgpro/ent-12/data/log/postgresql/postgresql-2022-01-* pgbadger --exclude-query="^(COPY|COMMIT)" /var/lib/pgpro/ent-12/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-12/data/log/postgresql-2022-01-25-0000.log cat /var/lib/pgpro/ent-12/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-12/data/log/postgresql-2022-08-21* pgbadger --prefix '%m %u@%d %p %r %a : ' /var/lib/pgpro/ent-12/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-12/data/log/postgresql-2022-08-21* # Use 8 CPUs to parse 10GB file faster pgbadger -j 8 /var/lib/pgpro/ent-12/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-12/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-12/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-12/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-12/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 option, where NN 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 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 N-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-12/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-12/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-12/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-12/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-12/data/log/postgresql-2022-01-23_10.log pgbadger -o day1/hour02.bin /var/lib/pgpro/ent-12/data/log/postgresql-2022-01-23_11.log pgbadger -o day1/hour03.bin /var/lib/pgpro/ent-12/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-12/data/log/postgresql-2022-01-14_000000.log
Options
This section describes pgbadger command-line options.
-aminutes--averageminutesSpecifies the number of minutes for which to build average graphs of queries and connections.
Default: 5.
-Aminutes--histo-averageminutesSpecifies the number of minutes for which to build histogram graphs of queries.
Default: 60.
-bdatetime--begindatetimeSpecifies the start date/time for the data to be parsed in logs.
-chost--dbclienthostOnly report on log entries for the specified client host.
-C--nocommentRemove /* ... */ comments from queries.
-dname--dbnamenameOnly report on log entries for the specified database.
-D--dns-resolvReplace client IP addresses with their DNS names.
Warning
This can considerably slow down pgbadger.
-edatetime--enddatetimeSpecifies the end date/time for the data to be parsed in logs.
-E--explodeBuild one report per each database. Global information not related to any database gets added to the
postgresdatabase report.-flogtype--formatlogtypeSpecifies the log type.
Possible values:
syslog,syslog2,stderr,jsonlog,csv,pgbouncer,logplex,rdsandredshift. Use when pgbadger cannot detect the log format.-G--nographDisables graphs in HTML output.
-h--helpShow detailed information about pbadger options and exit.
-Hpath--html-outdirpathSpecifies 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.-iname--identnameSpecifies the program name used to identify Postgres Pro messages in syslog logs.
Default:
postgres.-I--incrementalUse the incremental mode, where reports will be generated by days in a separate directory specified by the
-O/--outdiroption.-jnumber--jobsnumberSpecifies the number of jobs to run at same time. When working with csvlog logs, pgbadger always runs as single job.
Default: 1.
-Jnumber--JobsnumberSpecifies the number of log files to parse in parallel. When working with csvlog logs, one log at a time is processed.
Default: 1.
-lfilename--last-parsedfilenameSpecifies 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.
-Lfilename--logfile-listfilenameSpecifies the file containing the list of log files to parse.
-msize--maxlengthsizeSpecifies the maximum length of a query in reports. Longer queries will be truncated.
Default: 100000.
-M--no-multilineTurns off collecting multiline statements to avoid reporting excessive information, especially on errors that generate a huge report.
-Nname--appnamenameOnly report on log entries for the specified application.
-ofilename--outfilefilenameSpecifies the filename for the output and determines the report file format. Can be used multiple times to output several formats. For the
jsonoutput, ensure that the Perl moduleJSON::XSis installed. To dump the output to stdout, use the value of “-” as filename.Default:
out.html,out.txt,out.bin,out.jsonorout.tsung,for the respective output format.
-Opath--outdirpathSpecifies the directory where the out file must be saved.
-pstring--prefixstringSpecifies 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 standardlog_line_prefixstrings, for example, if your prefix includes additional variables, such as client IP or application name.-P--no-prettifyDisables SQL query code prettifier.
-q--quietDisables printing anything to stdout, even the progress bar.
-Q--query-numberingAdd numbering of queries to the output when used together with
--dump-all-queriesor--normalized-only.-raddress--remote-hostaddressSpecifies the host to execute the
catcommand on a remote log file to parse the file locally.-Rnumber--retentionnumberSpecifies 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).
-snumber--samplenumberSpecifies the number of query samples to store.
Default: 3.
-S--select-onlyOnly report on SELECT queries.
-tnumber--topnumberSpecifies the number of queries to store/display.
Default: 20.
-Tstring--titlestringSpecifies the title of the HTML report page.
-uusername--dbuserusernameOnly report on log entries for the specified username.
-Uusername--exclude-userusernameSpecifies the username to exclude log entries for from the report. Can be used multiple times.
-v--verboseEnables the verbose or debug mode.
Default: off.
-V--versionShow pgbadger version and exit.
-w--watch-modeOnly report errors, just like Logwatch can do.
-W--wide-charEncode HTML output of queries in UTF8 to avoid Perl messages “Wide character in print”.
-xformat--extensionformatSpecfies the output format. Possible values:
text,html,bin,jsonortsung.Default:
html.-X--extra-filesIn the incremental mode, write CSS and JavaScript resources to the output directory as separate files.
-zcommand--zcatcommandSpecifies the full command to run the zcat program. Use if zcat, bzcat or unzip is outside of your
PATHdirectories.-Z+/-XX--timezone+/-XXSpecifies the number of hours from GMT for the timezone. Use to adjust date/time in JavaScript graphs.
--pie-limitnumberSpecifies the number such that instead of lower pie data the sum will be shown.
--exclude-queryregexpSpecifies the regular expression such that matching queries will be excluded from the report. For example: “^(VACUUM|COMMIT)”. Can be used multiple times.
--exclude-filefilenameSpecifies the path to the file that contains regular expressions to use to exclude matching queries from the report, one expression per line.
--include-queryregexpSpecifies the regular expression such that only matching queries will be included in the report. Can be used multiple times. For example: “(tbl1|tbl2)”.
--include-filefilenameSpecifies the path to the file that contains regular expressions to use to include matching queries in the report, one expression per line.
--disable-errorTurns off generation of an error report.
--disable-hourlyTurns off generation of an hourly report.
--disable-typeTurns off generation of a report on queries by type, database and user.
--disable-queryTurns off generation of query reports, such as slowest or most frequent queries, queries by users, by database and so on.
--disable-sessionTurns off generation of a session report.
--disable-connectionTurns off generation of a connection report.
--disable-lockTurns off generation of a lock report.
--disable-temporaryTurns off generation of a report on temporary files.
--disable-checkpointTurns off generation of checkpoint/restartpoint reports.
--disable-autovacuumTurns off generation of an autovacuum report.
--charsetnameSpecifies the HTML charset to be used.
Default: utf-8.
--csv-separatorcharSpecifies the CSV field separator.
Default: “,”.
--exclude-timeregexpSpecifies 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-timeregexpSpecifies 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-dbnameSpecifies the name of the database to exclude related log entries from the report. For example: “outdated_db”. Can be used multiple times.
--exclude-appnamenameSpecifies the name of the application to exclude related log entries from the report. For example: “pg_dump”. Can be used multiple time.
--exclude-lineregexpSpecifies the regular expression such that any matching log entry will be excluded from the report. Can be used multiple times.
--exclude-clientaddressSpecifies the client IP/name to exclude related log entries from the report. Can be used multiple times.
--anonymizeObscure all literals in queries. Useful to hide confidential data.
--noreportPrevents generation of reports in the incremental mode.
--log-durationAssociate log entries generated by
andlog_duration= on.log_statement= all--enable-checksumAdd the MD5 sum under each query report.
--journalctlcommandSpecifies the command to produce the information similar to what the Postgres Pro log file contains. Usually, like this:
journalctl -u postgrespro-ent-12.--pid-dirpathSpecifies the path to store the PID file.
Default:
/tmp.--pid-filefilenameSpecifies the name of the PID file to manage concurrent execution of pgbadger.
Default:
pgbadger.pid.--rebuildRebuild all HTML reports in incremental output directories that contain binary data files.
--pgbouncer-onlyOnly show pgbouncer-related menu in the header.
--start-mondayIn the incremental mode, start calendar weeks on Monday. By default, they start on Sunday.
--iso-week-numberIn the incremental mode, start calendar weeks on Monday 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-onlyOnly dump all normalized queries to
out.txt.--log-timezone+/-XXSpecifies 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.
--prettify-jsonPrettify JSON output.
--month-reportYYYY-MMSpecifies 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-reportYYYY-MM-DDSpecifies 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.
--noexplainAvoid processing log lines generated by auto_explain.
--commandcmdSpecifies 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-weekAvoid building weekly reports in the incremental mode. Use if building weekly reports takes too long.
--explain-urlURLSpecifes the URL to override the URL of the graphical explain tool.
Default:
http://explain.depesz.com/?is_public=0&is_anon=0&plan=--tempdirpathSpecifies the directory for temporary files.
Default:
File::Spec->tmpdir() || '/tmp'.--no-process-infoDisables changing the pgbadger process title to help identify this process. Useful for systems where changing process titles is not supported.
--dump-all-queriesDump all queries found in the log file to a text file, replacing bind parameters in the queries at their respective placeholder positions.
--keep-commentsRetains comments in normalized queries. Useful to distinguish between same normalized queries.
--no-progressbarDisables displaying the progress bar.
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-programsshSpecifies the path to the SSH program to use.
Default: ssh.
--ssh-portportSpecifies the SSH port for the connection.
Default: 22.
--ssh-userusernameSpecifies the username for the connection.
Default: user running pgbadger.
--ssh-identityfilenameSpecifies the path to the identity file.
--ssh-timeoutsecondsSpecifies the timeout in seconds in case of the SSH connection failure.
Default: 10.
--ssh-optionoptionsSpecifies 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 <gilles@darold.net>