DEV Community

Dmitry Romanoff
Dmitry Romanoff

Posted on

How to parse Postgres log file and to print all the errors along with a specified number of lines before and after each error?

When working with PostgreSQL databases, it is important to check the log files.

Here is a bash script that parses the log file and prints all the errors along with a specified number of lines after each error.

#!/bin/bash

log_file="/tmp/my_postgres_aws_rds_log_file.log"
error_pattern="ERROR:"                # Pattern to search for errors
lines_before_error=2                  # Number of lines to print before each error
lines_after_error=3                   # Number of lines to print after each error

grep -B "$lines_before_error" -A "$lines_after_error" "$error_pattern" "$log_file"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)