The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a script to format JSON logs

Here’s a simple and customizable Python script to format JSON logs for readability. It takes raw JSON log lines (either from a file or standard input), parses them, and prints them in a human-readable format.

python
import json import sys import argparse def format_json_log_line(line, indent=4): try: log_entry = json.loads(line) formatted = json.dumps(log_entry, indent=indent, ensure_ascii=False) return formatted except json.JSONDecodeError: return f"Invalid JSON: {line.strip()}" def process_file(file_path, indent=4): with open(file_path, 'r', encoding='utf-8') as f: for line in f: formatted = format_json_log_line(line, indent) print(formatted) print('-' * 80) # separator between entries def process_stdin(indent=4): print("Reading from stdin. Press Ctrl+D (Linux/macOS) or Ctrl+Z (Windows) to stop.") for line in sys.stdin: formatted = format_json_log_line(line, indent) print(formatted) print('-' * 80) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Format JSON log entries for readability.") parser.add_argument('-f', '--file', help="Path to the log file containing JSON lines.") parser.add_argument('-i', '--indent', type=int, default=4, help="Number of spaces for indentation.") args = parser.parse_args() if args.file: process_file(args.file, args.indent) else: process_stdin(args.indent)

Features:

  • Supports reading from a file or standard input

  • Pretty-prints valid JSON with configurable indentation

  • Identifies and flags invalid JSON lines

  • Adds a visual separator for better readability

Usage:

  1. Save it as json_log_formatter.py

  2. Run from command line:

bash
# Format a log file python json_log_formatter.py --file mylogs.json # Format with 2-space indentation python json_log_formatter.py --file mylogs.json --indent 2 # Or use it with piped logs cat mylogs.json | python json_log_formatter.py

Let me know if you want an extended version with colorized output or filtering.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About