plog

package
v0.0.0-...-53891da Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

README

plog

A pretty-printer for JSON logs with colorized output. Use it as a standalone CLI to pipe logs through, or as a slog.Handler for direct integration in Go applications.

Installation

CLI
go install github.com/speakeasy-api/gram/plog/cmd/plog@latest
Library
go get github.com/speakeasy-api/gram/plog

CLI Usage

Pipe JSON logs through plog to format them:

# From a file
cat app.log | plog

# From a running process
./myapp 2>&1 | plog

# Filter to warnings and above
./myapp 2>&1 | plog --level=warn
Example

Input:

{"time":"2025-01-30T12:00:00.000Z","level":"info","msg":"Server started","port":8080}
{"time":"2025-01-30T12:00:01.000Z","level":"error","msg":"Connection failed","error":"timeout","host":"db.example.com"}

Output:

12:00:00.000 INFO  Server started
    port: 8080

12:00:01.000 ERROR Connection failed
    error: timeout
    host: db.example.com
CLI Flags
Flag Default Description
--level info Minimum level to display (trace, debug, info, warn, error, fatal)
--omit Comma-separated field patterns to omit (supports globs, e.g., *_id,secret*)
--level-keys level Comma-separated keys to look for log level
--message-keys msg,message Comma-separated keys to look for log message
--timestamp-keys time,ts,timestamp Comma-separated keys to look for timestamp
--source-keys source,caller Comma-separated keys to look for source location
--no-color false Disable colorized output

slog.Handler Integration

Use plog as a handler for Go's log/slog package:

package main

import (
    "log/slog"
    "github.com/speakeasy-api/gram/plog"
)

func main() {
    // Create a logger with pretty output
    logger := plog.DefaultLogger()

    logger.Info("Server started", "port", 8080)
    logger.Error("Connection failed", "error", "timeout")
}
Set as Default Logger
func main() {
    plog.SetDefault()

    slog.Info("Using the default logger", "key", "value")
}
With Options
logger := plog.DefaultLogger(
    plog.WithLevel(plog.LevelInfo),  // Suppress debug/trace
    plog.WithAddSource(true),            // Include source file:line
    plog.WithNoColor(true),              // Disable colors
)
Write to Custom Output
var buf bytes.Buffer
logger := plog.NewLogger(&buf, plog.WithNoColor(true))

Configuration Options

Option Description
WithLevel(level) Set minimum log level (use plog.LevelTrace, LevelDebug, LevelInfo, LevelWarn, LevelError, LevelFatal)
WithOmitKeys(patterns...) Field patterns to omit from output (supports globs, e.g., *_id, secret*)
WithAddSource(bool) Include source file and line number
WithNoColor(bool) Disable colorized output
WithOutput(io.Writer) Set output destination
WithLevelKeys(keys...) Keys to search for log level
WithMessageKeys(keys...) Keys to search for message
WithTimestampKeys(keys...) Keys to search for timestamp
WithSourceKeys(keys...) Keys to search for source location
WithWorkingDir(dir) Base directory for relative source paths
WithTheme(theme) Custom color theme (partial themes are merged with defaults)

Processing Existing Logs

Use PrettyPrint to process JSON logs from any io.Reader:

file, _ := os.Open("app.log")
defer file.Close()

plog.PrettyPrint(file,
    plog.WithLevel(plog.LevelWarn),
    plog.WithNoColor(true),
)

Features

  • Automatic timestamp parsing: RFC3339, Unix seconds/milliseconds/microseconds/nanoseconds
  • Flexible source locations: Parses both "file:line" strings and {"file":"...", "line":42} objects
  • Non-JSON passthrough: Lines that aren't valid JSON are passed through unchanged
  • Sorted attributes: Extra fields are displayed alphabetically for consistent output
  • Color themes: Customizable colors with hex code support

License

MIT

Documentation

Overview

Package plog provides pretty-printing for JSON lines logs with colorized output.

Index

Constants

View Source
const (
	LevelTrace = iota
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

Level constants for log severity.

Variables

This section is empty.

Functions

func DefaultLevelMap

func DefaultLevelMap() map[string]int

DefaultLevelMap returns the default mapping from level strings to level values.

func DefaultLogger

func DefaultLogger(opts ...Option) *slog.Logger

DefaultLogger creates a new slog.Logger with the pretty handler.

func NewConsoleLogger

func NewConsoleLogger(opts ...Option) *slog.Logger

NewConsoleLogger creates a logger that writes to stdout.

func NewLogger

func NewLogger(w io.Writer, opts ...Option) *slog.Logger

NewLogger creates a new slog.Logger that writes to the given writer.

func PrettyPrint

func PrettyPrint(r io.Reader, opts ...Option) error

PrettyPrint reads JSON lines from r and writes formatted output using the given options.

func SetDefault

func SetDefault(opts ...Option)

SetDefault sets the default slog logger to use the pretty handler.

Types

type Attr

type Attr struct {
	Key   string
	Value any
}

Attr represents a key-value attribute from a log record.

type Config

type Config struct {
	LevelKeys     []string
	LevelMap      map[string]int
	MessageKeys   []string
	TimestampKeys []string
	SourceKeys    []string
	OmitKeys      []string
	WorkingDir    string
	Output        io.Writer
	NoColor       bool
	HideTimestamp bool
	AddSource     bool
	Level         int
	Theme         Theme
	// contains filtered or unexported fields
}

Config holds the configuration for pretty-printing logs.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults.

func (*Config) ShouldOmit

func (c *Config) ShouldOmit(field string) bool

ShouldOmit returns true if the field name should be omitted from output.

type Formatter

type Formatter struct {
	// contains filtered or unexported fields
}

Formatter formats log records for output.

func NewFormatter

func NewFormatter(cfg *Config) *Formatter

NewFormatter creates a new Formatter with the given config.

func (*Formatter) Format

func (f *Formatter) Format(w io.Writer, record *Record) error

Format writes a formatted log record to the output.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler implements slog.Handler for pretty-printed output.

func NewHandler

func NewHandler(opts ...Option) *Handler

NewHandler creates a new slog Handler with the given options.

func (*Handler) Enabled

func (h *Handler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (*Handler) Handle

func (h *Handler) Handle(_ context.Context, r slog.Record) error

Handle formats and writes the log record.

func (*Handler) WithAttrs

func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Handler with the given attributes added.

func (*Handler) WithGroup

func (h *Handler) WithGroup(name string) slog.Handler

WithGroup returns a new Handler with the given group name added.

type OmitMatcher

type OmitMatcher struct {
	// contains filtered or unexported fields
}

OmitMatcher matches field names against glob patterns with caching.

func NewOmitMatcher

func NewOmitMatcher(patterns []string) *OmitMatcher

NewOmitMatcher creates a new OmitMatcher with the given patterns.

func (*OmitMatcher) Match

func (m *OmitMatcher) Match(field string) bool

Match returns true if the field name matches any of the omit patterns.

type Option

type Option func(*Config)

Option is a functional option for configuring the pretty printer.

func WithAddSource

func WithAddSource(addSource bool) Option

WithAddSource enables adding source location to log output.

func WithHideTimestamp

func WithHideTimestamp(hide bool) Option

WithHideTimestamp disables timestamp rendering.

func WithLevel

func WithLevel(level int) Option

WithLevel sets the minimum level to display. Logs below this level will be suppressed.

func WithLevelKeys

func WithLevelKeys(keys ...string) Option

WithLevelKeys sets the keys to look for the log level.

func WithLevelMap

func WithLevelMap(m map[string]int) Option

WithLevelMap sets the mapping from level strings to level values.

func WithMessageKeys

func WithMessageKeys(keys ...string) Option

WithMessageKeys sets the keys to look for the log message.

func WithNoColor

func WithNoColor(noColor bool) Option

WithNoColor disables colorized output.

func WithOmitKeys

func WithOmitKeys(patterns ...string) Option

WithOmitKeys sets field name patterns to omit from output. Supports glob patterns (e.g., "request.*", "*_id", "secret*").

func WithOutput

func WithOutput(w io.Writer) Option

WithOutput sets the output writer.

func WithSourceKeys

func WithSourceKeys(keys ...string) Option

WithSourceKeys sets the keys to look for the source location.

func WithTheme

func WithTheme(theme Theme) Option

WithTheme sets the color theme. Any zero-value fields in the provided theme are filled from the default theme.

func WithTimestampKeys

func WithTimestampKeys(keys ...string) Option

WithTimestampKeys sets the keys to look for the timestamp.

func WithWorkingDir

func WithWorkingDir(dir string) Option

WithWorkingDir sets the working directory for relative source paths.

type Record

type Record struct {
	Level    int
	LevelRaw string
	Message  string
	Time     time.Time
	Source   *Source
	Attrs    []Attr
}

Record represents a parsed log record.

func Parse

func Parse(line []byte, cfg *Config) (*Record, error)

Parse parses a JSON log line into a Record using the given config.

type Source

type Source struct {
	File     string
	Line     int
	Function string
}

Source represents a source code location.

func (*Source) RelativePath

func (s *Source) RelativePath(workingDir string) string

RelativePath returns the source file path relative to the working directory. For paths in the Go module cache, it formats them as "module@version:path/in/module".

func (*Source) String

func (s *Source) String() string

String returns the source location as a string.

type Theme

type Theme struct {
	Timestamp   lipgloss.Style
	LevelTrace  lipgloss.Style
	LevelDebug  lipgloss.Style
	LevelInfo   lipgloss.Style
	LevelWarn   lipgloss.Style
	LevelError  lipgloss.Style
	LevelFatal  lipgloss.Style
	Message     lipgloss.Style
	Source      lipgloss.Style
	AttrKey     lipgloss.Style
	AttrValue   lipgloss.Style
	AttrBracket lipgloss.Style
}

Theme defines the color styles for log output.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme returns a theme with hex colors.

Directories

Path Synopsis
cmd
plog command
Command plog pretty-prints JSON lines logs with colorized output.
Command plog pretty-prints JSON lines logs with colorized output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL