PostgreSQL log analysis with pgBadger: when your logs answer the performance question
When users report slow periods or lock complaints and nobody can name a cause, the answer is often already in the PostgreSQL log files, just unread. pgBadger parses PostgreSQL log files into HTML reports, and how useful those reports are depends entirely on the logging settings PostgreSQL writes in the first place. A default configuration records little about statement duration, lock waits or checkpoints, so the reader's first task is deciding what to log before any report can be trusted.
Teams usually need pgBadger when the question is about history: which statements were slow last Tuesday, which query shapes dominate the load, or whether lock waits clustered around a batch job. Log analysis answers these retrospective questions well because it works from the events PostgreSQL recorded. A metrics stack such as Prometheus with Grafana fits better for continuous trends and alerting, and the pg_stat views fit better for the current state of sessions, locks and table statistics. Most mature setups use more than one of these, and the choice depends on whether the question is "what happened" or "what is happening now".
Before committing to pgBadger, confirm three things with the team that owns the cluster: which PostgreSQL major version runs in production, whether log files are retained long enough to cover the incident window, and whether the team can accept the disk, I/O and log shipping cost of richer logging. Those answers decide whether the logs can support the analysis at all. The sibling topic on logging configuration covers which events to record, so this page focuses on turning the recorded events into reports you can act on.
Logging settings and pgBadger options and when each fits
This table compares the PostgreSQL logging settings and pgBadger command options that shape a log analysis report. Read each row as a decision: what to choose, when it fits, and how much log volume it adds. The main takeaway is that the richer the logging, the more useful the report and the larger the log volume, so the choices should match the questions you need answered.
| Setting or option | When to choose it | Log volume cost |
|---|---|---|
| logging_collector and log destination | Choose the collector when you want PostgreSQL to write log files that pgBadger can read directly, typically with csvlog or stderr output. | Adds disk writes and rotation work. Confirm where files land and how long they are kept. |
| log_line_prefix | Set a prefix with timestamp, process ID, user, database and application name when you need to attribute slow queries and lock waits. pgBadger needs the prefix to match its parsing format. | Small per-line cost, but it multiplies across every logged line. Keep fields you will filter on. |
| log_min_duration_statement | Use a threshold to log only slow statements for performance review. A low threshold gives broad coverage but produces the largest log files. | Grows with statement volume and threshold. Raise the threshold on busy systems and revisit it after tuning. |
| log_lock_waits | Enable when you need to see which sessions waited on locks and for how long, which feeds the lock section of the report. | Adds entries only when a wait exceeds the deadlock timeout, so volume is usually modest. Confirm the timeout in your version. |
| log_checkpoints | Enable when you want checkpoint timing and write volume in the checkpoint section, useful for I/O and WAL sizing questions. | Adds a few lines per checkpoint, so volume is predictable and low on most systems. |
| log_autovacuum_min_duration | Enable when you suspect vacuum activity is causing I/O spikes or long-running maintenance. | Volume depends on how many tables are vacuumed above the threshold. Start with a higher threshold to limit noise. |
| Single report file | Choose a single report when you analyze one bounded log set, such as an incident window or a short test period. | No extra storage beyond the report itself, but very large logs take longer to parse each run. |
| Incremental reports | Choose incremental mode for recurring reports on a live server so each run only processes new log data, with saved state between runs. | Requires persistent storage for the state and report directory. Confirm the directory is writable and backed up. |
| Per-day reports | Choose per-day output when you need to compare days or review a specific date without reparsing the full history. | Creates one report set per day, so storage for reports grows steadily over time. Plan a retention rule. |
Setting up pgBadger on a self-hosted PostgreSQL server
This sequence moves PostgreSQL logs from default settings to a first pgBadger report and then to scheduled incremental runs. Each step ends with a check so you know the data is usable before you rely on the reports.
Confirm the log destination and rotation
The database administrator checks where the server writes its logs, which is set by logging_collector, log_directory and log_filename, and confirms that rotation by time or size is enabled so files do not grow without limit. Record the path and the rotation interval, because the scheduled pgBadger job will read from exactly this location. The step is done when you can list the current log file on the server and see recent entries from the running instance.
Set log_line_prefix and logging parameters
Set log_line_prefix so each line carries the timestamp, process ID, user, database, application name and client host, which pgBadger needs to group sessions and users. Then set log_min_duration_statement to capture slow statements, log_lock_waits to record lock waits, and log_checkpoints and log_autovacuum_min_duration to capture checkpoint and vacuum activity. Confirm the exact prefix format against the pgBadger documentation for your version, since the parser depends on it. Changes are made in postgresql.conf or with ALTER SYSTEM by the database administrator, and the step is done when the saved file contains these settings.
Reload the configuration and verify settings
Apply the changes with pg_reload_conf() or a configuration reload, which does not need a restart for these parameters. Confirm in pg_settings that each parameter shows the new value and that the source is the configuration file or ALTER SYSTEM. Note that changing logging_collector itself requires a restart, so check that separately if you changed it. The step is done when the settings query returns the values you chose for every logging parameter.
Check that expected events appear in the log
Before building any report, run a controlled test: execute a query that exceeds the slow-statement threshold, open a transaction that waits on a lock held by another session, and trigger a checkpoint or a manual CHECKPOINT. Open the current log file and confirm that the slow statement, the lock wait and the checkpoint lines appear with the prefix fields populated. If a category is missing, return to the previous step, because a report built from incomplete logs will hide the problems you are looking for.
Copy logs and generate the first report
Copy a set of rotated log files to a separate analysis host so pgBadger does not compete with the database server for disk and CPU. Run pgbadger against the copied files with an output path for the HTML report, and use the options that match your log format and time range. Open the report and confirm that the sections for slow queries, lock activity and checkpoints contain entries that match the test events from the previous step. The step is done when the report opens in a browser and those sections are populated.
Schedule incremental runs and retain output
Configure pgBadger in incremental mode so each scheduled run parses only new log content and adds it to the existing report, using a stored position file. Set a schedule through cron or a systemd timer, write output to a fixed directory, and keep the position file alongside it. Decide how long reports and copied logs are kept, since both consume storage and may contain query text that needs access control. The step is done when two consecutive scheduled runs complete and the second run adds new entries without repeating earlier ones.
Estimate log volume and set limits
Measure how many bytes the server writes per day under the new settings, using the size of the current log files and the rotation interval. Logging every statement or lock wait at low thresholds can increase this volume quickly, so review the thresholds against the disk and retention you have. Confirm with your storage team how much log space the server and the analysis host can hold, and set a retention rule that matches it. The step is done when you have a written daily volume figure from your own environment and a retention rule that uses it.
How log files flow from PostgreSQL into pgBadger reports
The diagram starts with PostgreSQL writing log lines according to log_line_prefix and logging settings, then passes through log rotation and a copy step into a directory that pgBadger reads. pgBadger parses new files incrementally into a report directory, and a reviewer opens the HTML output. The raw logs and the copy may contain sensitive values such as statement text and parameters, so access control applies at every hand-off after the server, not only to the final report.
Log movement from the server to a reviewer, with sensitive-data boundaries.
Reading the slow query, lock and checkpoint sections
The slow query sections list statements whose logged duration crossed the threshold you set with log_min_duration_statement. pgBadger groups statements after normalizing them, replacing literal values with placeholders, so that thousands of calls to the same query shape appear as one entry with a count, total time and average time. Grouping by total time shows where the database spends its effort overall, while grouping by average time shows individual statements that are slow each time they run. Both views matter because a fast query run millions of times can cost more than a slow query run once a day.
- What counts: only statements logged above the threshold appear, so a report cannot show queries you never logged. Confirm the threshold and whether
log_durationorlog_min_duration_statementis set. - Normalized grouping: check that the top entries are real query shapes and not a mix of unrelated statements.
- Total versus average time: rank by total time for capacity questions and by average time for user-facing latency.
- Sample statements: compare the example bind values in the entry with the parameters your application sends before drawing conclusions.
- Client and application context: match the slow entries to the application or user that issued them, if your
log_line_prefixrecords that.
Before changing any setting or index, verify that the statement is slow under normal load, check its execution plan with EXPLAIN ANALYZE in a safe environment and confirm the wait is not caused by locks or I/O outside the query itself.
Lock entries record sessions that waited longer than deadlock_timeout to acquire a lock, which PostgreSQL logs when lock waits are enabled with log_lock_waits. A lock wait entry names the waiting process, the blocking process where it is known, the lock type and the statement involved. A single wait is often normal, since sessions briefly queue behind DDL, vacuum or row updates. A repeated pattern on the same table, or a long chain of waiters behind one session, usually means a transaction is holding a lock open longer than it should.
- What the entry means: a session waited for a lock held by another session for longer than the deadlock check interval.
- Repeated tables: a single relation appearing often points to a migration, a long-running report or application code that holds transactions open.
- Blocking statements: check whether the blocker was an idle transaction, a schema change or a batch job.
- Deadlock entries: these are separate from waits and show that PostgreSQL resolved a cycle by aborting one transaction. Check the application retry logic.
- Timing against other events: correlate the lock window with backups, deployments and autovacuum activity in the same log period.
When the report shows lock waits, check pg_stat_activity and pg_locks on the live server if you can reproduce the event, and review transaction duration in the application code. Treat the entry as a pointer to a session pattern, not a diagnosis, and confirm the cause before changing lock timeouts.
Checkpoint sections summarize how often PostgreSQL wrote dirty buffers to disk and how much data each checkpoint flushed. These entries come from the server's logging of checkpoint starts and completions, enabled with log_checkpoints. The report typically shows the number of checkpoints, the reason each one ran, the write and sync times and the volume of buffers written. Checkpoints triggered by max_wal_size being reached, rather than by the timed interval set with checkpoint_timeout, often indicate that WAL volume is higher than the configured budget.
- Frequency and trigger: compare timed checkpoints with those forced by WAL volume to see which limit is driving activity.
- Write and sync times: long write or sync phases suggest storage that cannot absorb the flush rate, which is a storage question before it is a tuning question.
- Buffers written: large volumes per checkpoint point to heavy write activity, such as bulk loads or wide updates.
- Warnings in the log: messages saying checkpoints occur too frequently are a direct signal that
max_wal_sizeshould be reviewed. - Time window: a checkpoint spike that matches a batch job is different from a steady pattern, so compare against your workload calendar.
Before changing max_wal_size, checkpoint_timeout or checkpoint_completion_target, verify the WAL generation rate, the free disk space that a larger WAL budget would consume and the recovery time you are willing to accept after a crash. Changing checkpoint settings moves I/O in time and does not reduce the total work the workload creates.
What log volume costs and what drives it up
Logging more detail makes pgBadger reports more useful, but every extra line adds disk, retention, processing time and tuning work. The cards below separate the cost components, who pays for each, and the settings that push volume up, so you can ask a partner or your own team for a quote that reflects your real log rate.
Disk space and retention
Log files grow with every logged statement, connection and lock wait, and they accumulate until rotation or deletion removes them. Retention length is usually the largest multiplier, because a longer window keeps more days of raw logs on the database host. Ask for your current daily log volume measured over a normal business week and a peak week, then calculate retention against the disk you can spare, leaving room for WAL and data growth.
CPU and time for pgBadger
pgBadger parses the log text to build its reports, so run time and memory grow with the size of the input. A full historical parse on a busy server can take far longer than the daily incremental run, and it competes with the database for CPU if it runs on the same host. Decide where reports are generated, how long a run may take, and whether it runs on a copy of the logs rather than the production server.
Shipping and central storage
Once logs leave the database host for a SIEM, object store or central log server, you pay for network transfer, ingestion and storage on that side too, often at a different rate than local disk. Shipping also duplicates data if raw logs stay local. Confirm which system is the system of record, whether pgBadger reads local files or a shipped copy, and what the receiving platform charges for ingestion and retention.
Lowering the slow-statement threshold
Setting log_min_duration_statement to a small value, such as a few milliseconds, logs almost every query on a busy application and multiplies volume quickly. A higher threshold keeps the log focused on statements that matter for tuning. Start from the threshold your team can act on, review how many entries it produces per day, and adjust before you rely on the report.
Logging all statements and connections
Setting log_statement to all records every statement, which adds the most volume and can expose sensitive values in plain text. Connection and disconnection logging on a pool that opens and closes connections constantly produces a line for each event, so a connection pooler such as PgBouncer can turn a small logging setting into a large file. Enable these settings only for a defined investigation or audit need, and time-box them.
Engineering time to tune thresholds
Choosing thresholds, the log_line_prefix format and the rotation schedule takes repeated review: you run a report, read the sections, change a setting and check the volume again. This effort is mostly one-time setup followed by periodic review after workload changes. When you ask for a quote, include the number of tuning cycles, who signs off on sensitive logging, and whether the handover includes a documented baseline.
Questions buyers ask about pgBadger log analysis
How much effort does pgBadger log analysis setup take, and what drives it?
Installing pgBadger is the small part. Most of the effort goes into deciding what PostgreSQL should log, then testing that logging against real traffic. The main drivers are the number of clusters and databases, how much your current logging already captures, whether logs arrive in one format across all servers, and how many people need to review the reports. Teams with a single cluster and existing log_line_prefix settings usually have less to change than teams with many servers, mixed PostgreSQL versions or logs that rotate in unusual ways. Ask any partner to split their quote into logging design, report generation and handover.
Can our internal database team run pgBadger without outside help?
Often yes, if the team already administers PostgreSQL and can change server configuration. pgBadger is a Perl tool that reads log files and writes HTML reports, so the technical bar is moderate. The harder parts are judgment calls: choosing a slow query threshold that avoids noise, deciding which statements may be logged without exposing sensitive values, and reading lock and checkpoint sections correctly. If nobody on the team has time to own those decisions and repeat the reports on a schedule, the work tends to stall after the first report.
What does the work need from our team?
Plan for three things. First, access to log files from each cluster, including rotation settings and where logs are stored. Second, a test window where logging can be raised temporarily, since verbose settings add load and file volume. Third, sign-off from the database owner and the security or compliance lead on the final logging settings, because some logged statements can contain personal or sensitive data. Your team should also name who receives the reports and who acts on them.
How long should we plan for a pgBadger rollout?
The duration depends on how many servers are in scope, how quickly you can agree on logging settings, and whether the test window can start soon. Ask any provider for a timeline tied to a written scope, with dates for the logging review, the test window and the handover. Changes to logging settings usually need a review cycle with the database and security owners, so that step often takes longer than the install.
What drives the cost of logs and tooling for pgBadger?
pgBadger itself is open source, so the main costs are labor and infrastructure. Labor covers logging design, testing, report scheduling and handover. Infrastructure covers disk space and retention for log files, the server or job that runs incremental parsing, and storage for published reports. Verbose settings such as logging every statement increase log volume, which raises storage, shipping and retention costs and can slow the database. Ask for a quote that lists the one-time setup work separately from any recurring review of reports and retention policy.
When should we bring in outside help for PostgreSQL log analysis?
Consider outside help when you need logging that passes review by security, audit or compliance teams, when several clusters must follow one standard, or when slow queries and lock waits keep recurring and nobody has time to find the cause. Outside help is also useful when the logs contain sensitive values that must be kept out of the output. DeployOpen implements and documents self-hosted PostgreSQL inside your own infrastructure, including logging configuration, and can produce handover documentation your team keeps. Confirm during scoping which parts your team will run after handover.
Will pgBadger find every performance problem in our database?
No. pgBadger only reports what PostgreSQL logged, so its findings depend on the logging settings. Slow query, lock and checkpoint sections show problems only when the relevant thresholds are set and the events occur during the logged period. Before acting on a finding, confirm it with live statistics or a repeat test, and ask your provider which problems the chosen settings would miss.
When pgBadger fits better than metrics or a log platform
pgBadger answers after-the-fact questions from log files, while metrics and centralized log search answer whether something is happening right now. Use pgBadger when you need a report of what ran last Tuesday between 02:00 and 03:00, which query shapes dominated lock waits, or how checkpoints clustered during a batch window. Prometheus with Grafana, Zabbix or Graylog fits better when you need a time series that is always collected, dashboards that a shift team watches, or an alert that fires before users notice. The two approaches consume different inputs. pgBadger needs the statements and events that PostgreSQL wrote to its log, so its value depends on the logging settings you chose. Metrics depend on a monitoring role and an exporter or receiver that scrapes counters continuously.
The decision is rarely either-or. Ask which question must be answered within minutes and which question is asked after an incident review or during a capacity study. For the first, plan alerting and metrics. For the second, plan a log report that someone runs on a schedule. Confirm with your own platform team whether logs already flow to a central system such as Graylog, because a centralized copy may make on-demand pgBadger runs simpler, and confirm your retention period, since a report can only cover the log history you kept. The sibling pages on PostgreSQL logging configuration and PostgreSQL alerting cover the other half of this decision: what PostgreSQL should write to its log, and which conditions should page someone.
How DeployOpen scopes and delivers PostgreSQL log analysis
DeployOpen treats pgBadger reporting as part of the database's logging design, not a standalone report. We agree what the logs must answer, configure PostgreSQL to produce them, and hand over a repeatable report run in infrastructure you control.
How we scope
- Review which questions the reports must answer, such as slow queries, lock waits or checkpoint pressure.
- Inventory current logging settings, log destinations, rotation and the PostgreSQL version in use.
- Agree in writing the servers covered, the log volume and retention period, and who receives the reports.
How we build
- Set log_line_prefix and logging parameters so pgBadger can parse each log entry on the target servers.
- Configure the incremental report run and its output location, then confirm it reads rotated logs correctly.
- Test reports against known slow statements and lock waits to confirm the sections reflect real activity.
How we hand over
- Document the logging settings, parser format, report schedule and where each output is stored.
- Walk your database and operations staff through reading the slow query, lock and checkpoint sections.
- Record log volume and storage growth observed during testing so you can plan retention and disk capacity.
How we support
- Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
- Ongoing support, upgrades and log review can be provided as a retainer after handover.
- Confirm with your team whether reports must be retained or shipped to a SIEM under your own policy.

