Created
October 29, 2025 08:52
-
-
Save aryomuzakki/d96a1158a60be7077e333b0fde8a4e45 to your computer and use it in GitHub Desktop.
bash script to read log from pino logger using pino-pretty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| set -euo pipefail | |
| # Always restore terminal on exit (even if pipeline fails / Ctrl-C) | |
| cleanup() { | |
| # restore sane TTY and cursor, reset terminal if needed | |
| stty sane || true | |
| tput cnorm || true | |
| } | |
| trap cleanup EXIT | |
| # Default log directory | |
| LOG_DIR="${1:-$HOME/repo/project/logs}" | |
| FOLLOW="${2:-}" | |
| # Pick a pino-pretty binary | |
| if command -v pino-pretty >/dev/null 2>&1; then | |
| PRETTY_BIN="pino-pretty" | |
| elif [ -x "./node_modules/.bin/pino-pretty" ]; then | |
| PRETTY_BIN="./node_modules/.bin/pino-pretty" | |
| else | |
| echo "pino-pretty not found. Install it: npm i -D pino-pretty" | |
| exit 1 | |
| fi | |
| # Pick a zcat variant | |
| if command -v zcat >/dev/null 2>&1; then | |
| ZCAT="zcat" | |
| elif command -v gzcat >/dev/null 2>&1; then | |
| ZCAT="gzcat" | |
| else | |
| echo "zcat/gzcat not found. Install gzip: sudo apt-get install gzip" | |
| exit 1 | |
| fi | |
| # Build file list safely (only files) | |
| mapfile -t FILES < <(find "$LOG_DIR" -maxdepth 1 -type f \( \ | |
| -name '*.log.gz' -o -name '*.log' -o -name '*.txt' \) | sort) | |
| if [ "${#FILES[@]}" -eq 0 ]; then | |
| echo "No log files found in: $LOG_DIR" | |
| exit 0 | |
| fi | |
| # Show historical logs + (optional) follow app.log | |
| if [ "$FOLLOW" = "--follow" ] || [ "$FOLLOW" = "-f" ]; then | |
| if [ -f "$LOG_DIR/app.log" ]; then | |
| { "$ZCAT" -f "${FILES[@]}"; tail -n +1 -F "$LOG_DIR/app.log"; } \ | |
| | "$PRETTY_BIN" --colorize \ | |
| | less -RS +G | |
| else | |
| "$ZCAT" -f "${FILES[@]}" \ | |
| | "$PRETTY_BIN" --colorize \ | |
| | less -RS +G | |
| fi | |
| else | |
| "$ZCAT" -f "${FILES[@]}" \ | |
| | "$PRETTY_BIN" --colorize \ | |
| | less -RS +G | |
| fi |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Guide
Download the Script:
Edit
.bashrc:nano ~/.bashrcAdd the following at the end:
Apply Changes:
Run the Script: