prettylog

package module
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2025 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

prettylog

Golang Slog Log Formatter

Documentation

Overview

Package prettylog provides a pretty-printed structured logging handler for Go's standard library slog package.

prettylog offers customizable formatting, coloring, and modular entry writers for beautiful console output. It implements the slog.Handler interface and can be used as a drop-in replacement for other slog handlers.

Features

  • Colorized output with terminal detection
  • Modular entry writers for different log components
  • Configurable time, function, and file/line formatting
  • Pretty-printed JSON for structured data
  • Thread-safe operation with buffer pooling
  • Extensive customization through variadic options

Basic Usage

The simplest way to use prettylog is to create a handler with default settings:

handler := prettylog.New()
logger := slog.New(handler)
logger.Info("Hello, world!", "key", "value")

Configuration Options

prettylog supports extensive customization through options:

handler := prettylog.New(
    // Pass information to writers that this is the package that uses this logger. DefaultFunctionWriter will shorten function name if it starts with the package name.
    prettylog.WithPackageName("github.com/tigorlazuardi/prettylog"),
    prettylog.WithLevel(slog.LevelDebug),
    prettylog.WithOutput(os.Stdout),
    prettylog.WithAddSource(true),
)

Available configuration options:

  • WithPackageName(string): Set package name for function trimming
  • WithOutput(io.Writer): Set output destination
  • WithLevel(slog.Level): Set minimum log level
  • WithAddSource(bool): Enable/disable source information
  • WithReplaceAttr(func): Set attribute replacement function
  • WithHandlerOptions(*slog.HandlerOptions): Set complete handler options
  • WithColor(bool): Enable/disable colored output
  • WithPoolSize(int): Set buffer pool size

Writer Management

You can customize log components by managing entry writers:

// Replace all writers with custom ones
handler := prettylog.New(
    prettylog.WithWriters(myLevelWriter, myMessageWriter),
)

// Add additional writers to defaults
customWriter := prettylog.NewCommonWriter(myFormatter).
    WithStaticKey("Custom").
    WithValueColorizer(prettylog.BoldColoredStyler)

handler := prettylog.New(
    prettylog.WithAdditionalWriters(customWriter),
)

// Remove specific writers from defaults
handler := prettylog.New(
    prettylog.WithoutWriters(prettylog.DefaultTimeWriter),
)

// Replace specific writers
handler := prettylog.New(
    prettylog.ReplaceWriter(prettylog.DefaultLevelWriter, myLevelWriter),
)

Writer management options:

  • WithWriters(...EntryWriter): Replace all writers
  • WithAdditionalWriters(...EntryWriter): Add to existing writers
  • WithoutWriters(...EntryWriter): Remove specific writers
  • ReplaceWriter(old, new): Replace a specific writer

Entry Writers

prettylog uses a modular system of EntryWriter components:

  • DefaultLevelWriter: Log level with background color
  • DefaultMessageWriter: Log message with level-based color
  • DefaultTimeWriter: Timestamp in configurable format
  • DefaultFunctionWriter: Function name with optional package trimming
  • DefaultFileLineWriter: File path and line number
  • DefaultPrettyJSONWriter: Pretty-printed JSON for structured data

Each writer can be individually customized using their With* methods or replaced entirely.

Color Support

prettylog automatically detects terminal capabilities and enables colors when appropriate.

Color support can be explicitly controlled:

// Force colors off
handler := prettylog.New(prettylog.WithColor(false))

// Force colors on
handler := prettylog.New(prettylog.WithColor(true))

// Auto Detect when Cloning.
clonedHandler := handler.Clone(
	prettylog.WithOutput(os.Stdout),
	prettylog.WithColor(prettylog.CanColor(os.Stdout)),
)

Color is automatically detected on New, but not when using Handler.Clone method.

Performance

prettylog uses buffer pooling to minimize memory allocations during logging. The pool size can be configured:

handler := prettylog.New(
    prettylog.WithPoolSize(32 * 1024 * 1024), // 32MB pool
)

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultFileLineWriter = NewFileLineWriter()

DefaultFileLineWriter is the default entry writer for file and line information. It uses short format and includes the "File" key.

View Source
var DefaultFunctionWrtier = NewFunctionWriter()

DefaultFunctionWrtier is the default entry writer for function names. It uses short function format and includes the "Function" key.

View Source
var DefaultLevelWriter = NewCommonWriter(DefaultLevelValuer).
	WithValueColorizer(BackgroundBoldColoredStyler)

DefaultLevelWriter is the default entry writer for log levels. It displays the log level with background bold colored styling.

View Source
var DefaultMessageValuer = func(info RecordData) string {
	return info.Record.Message
}

DefaultMessageValuer extracts the log message from RecordData. This is the default value formatter used by DefaultMessageWriter.

View Source
var DefaultMessageWriter = NewCommonWriter(DefaultMessageValuer).
	WithValueColorizer(SimpleColoredStyler)

DefaultMessageWriter is the default entry writer for log messages. It displays the log message with simple color styling based on log level.

View Source
var DefaultNewLineWriter = NewCommonWriter(AddNewLineFormat)
View Source
var DefaultPrettyJSONWriter = NewPrettyJSONWriter()

DefaultPrettyJSONWriter is the default entry writer for pretty-printed JSON output of log attributes. It excludes standard slog keys (time, level, message, source) and formats the remaining attributes as colored JSON.

View Source
var DefaultTimeWriter = NewTimeWriter()

DefaultTimeWriter is the default entry writer for timestamps. It uses time-only format and includes the "Time" key.

DefaultWriters is the default set of entry writers used by new handlers. It includes writers for level, message, time, function, file/line, and pretty JSON output, and adds a new line at the end.

Functions

func AddNewLineFormat

func AddNewLineFormat(info RecordData) string

func BackgroundBoldColoredStyler

func BackgroundBoldColoredStyler(info RecordData, s string) string

BackgroundBoldColoredStyler applies background color with bold white text based on log level. Provides high contrast styling suitable for important information like log levels.

func BoldColoredStyler

func BoldColoredStyler(info RecordData, s string) string

BoldColoredStyler applies bold color styling based on the log level. Same colors as SimpleColoredStyler but with bold formatting.

func CanColor

func CanColor(w io.Writer) bool

CanColor determines if the given writer supports pretty output (i.e., is a terminal and has tty).

CanColor is called by New to determine if pretty output should be enabled (overrideable), but will not be called by Handler.Clone.

It does so by checking if the writer has an Fd() method and returns a file descriptor. This is typically implemented by os.File.

If the writer is wrapped (e.g., by a WriteLocker), it will attempt to unwrap if it implements interface { Unwrap() io.Writer }. If available, then this function will check the underlying writer. This repeats until a writer without Unwrap is found or a nil writer is encountered.

Example

ExampleCanColor demonstrates color detection functionality.

package main

import (
	"log/slog"
	"os"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	// Check if a writer supports color
	if prettylog.CanColor(os.Stdout) {
		handler := prettylog.New(
			prettylog.WithOutput(os.Stdout),
			prettylog.WithColor(true),
		)
		logger := slog.New(handler)
		logger.Info("Colorized output to stdout")
	} else {
		handler := prettylog.New(
			prettylog.WithOutput(os.Stdout),
			prettylog.WithColor(false),
		)
		logger := slog.New(handler)
		logger.Info("Plain output to stdout")
	}
}

func DefaultLevelFormatter

func DefaultLevelFormatter(info RecordData) string

DefaultLevelFormatter returns the string representation of the log level. It uses the standard slog level string representation.

func DefaultLevelValuer

func DefaultLevelValuer(info RecordData) string

DefaultLevelValuer extracts the log level as a string from RecordData. This is the default value formatter used by DefaultLevelWriter.

func DefaultMessageFormatter

func DefaultMessageFormatter(info RecordData) string

DefaultMessageFormatter returns the log message without any modifications.

func DefaultPrefix

func DefaultPrefix(info RecordData, this *CommonWriter) string

DefaultPrefix returns the default prefix between log entry components. It returns:

  • Empty string if buffer is empty
  • Newline if the writer has no key
  • Space for subsequent entries

func FullFileLineFormatter

func FullFileLineFormatter(info RecordData) string

FullFileLineFormatter returns the complete file path with line number. Format: "/full/path/to/file.go:123"

func FullFunctionFormat

func FullFunctionFormat(info RecordData) string

FullFunctionFormat returns the complete function name including package.

func FullFunctionFormatter

func FullFunctionFormatter(info RecordData) string

FullFunctionFormatter returns the complete function name including package. If the function information is not available, it returns an empty string.

func LongFileLineFormat

func LongFileLineFormat(info RecordData) string

LongFileLineFormat returns the complete file path with line number.

func PlainStyler

func PlainStyler(info RecordData, s string) string

PlainStyler returns the string unchanged without any styling. Useful when you want to disable styling for specific components.

func RFC3339TimeFormat

func RFC3339TimeFormat(info RecordData) string

RFC3339TimeFormat formats the timestamp in RFC3339 format.

func RFC3339TimeFormatter

func RFC3339TimeFormatter(info RecordData) string

RFC3339TimeFormatter returns the time in time.RFC3339 format.

func ShortFileLineFormat

func ShortFileLineFormat(info RecordData) string

ShortFileLineFormat returns file path and line number with working directory trimmed.

func ShortFileLineFormatter

func ShortFileLineFormatter(info RecordData) string

ShortFileLineFormatter returns the file path and line number with the current working directory trimmed when possible. If the working directory cannot be determined or is not a prefix of the file path, the full file path is returned. Format: "path/to/file.go:123"

func ShortFunctionFormat

func ShortFunctionFormat(info RecordData) string

ShortFunctionFormat returns the short function name if package name matches. If package name is empty or does not match, returns the full function name.

func SimpleColoredStyler

func SimpleColoredStyler(info RecordData, s string) string

SimpleColoredStyler applies color styling based on the log level. Colors: Error=Red, Warn=Yellow, Info=Green, Debug=Cyan, others=White.

func TimeOnlyFormatter

func TimeOnlyFormatter(info RecordData) string

TimeOnlyFormatter returns the time in time.TimeOnly format ("15:04:05").

func TimeOnlyTimeFormat

func TimeOnlyTimeFormat(info RecordData) string

TimeOnlyTimeFormat formats the timestamp in time.TimeOnly format ("15:04:05").

func TrimPrefixFunctionFormatter

func TrimPrefixFunctionFormatter(info RecordData) string

TrimPrefixFunctionFormatter returns the function name with the package name prefix trimmed. If the function information is not available, it returns an empty string.

Types

type CommonWriter

type CommonWriter struct {
	Key         Formatter
	Valuer      Formatter
	Prefix      PrefixFunc
	KeyStyler   Styler
	ValueStyler Styler
}

CommonWriter is a common implementation of EntryWriter that writes a key-value pair. It provides configurable formatting for both keys and values, along with styling options.

Use NewCommonWriter to create a new instance with proper field initialization, then customize it using the provided methods.

func NewCommonWriter

func NewCommonWriter(valuer Formatter) *CommonWriter

NewCommonWriter creates a new CommonWriter with the given value formatter. The value formatter extracts the actual value from the RecordData.

The key is empty by default and can be set using WithKey or WithStaticKey methods. Default styling uses bold colored keys and plain values.

func (*CommonWriter) KeyLen

func (cw *CommonWriter) KeyLen(info RecordData) int

func (*CommonWriter) WithKey

func (cw *CommonWriter) WithKey(f Formatter) *CommonWriter

WithKey sets the key formatter for this CommonWriter. The key formatter determines what key text is displayed for this log component.

func (*CommonWriter) WithKeyColorizer

func (cw *CommonWriter) WithKeyColorizer(c Styler) *CommonWriter

WithKeyColorizer sets the styler for the key portion of this CommonWriter. The key styler applies colors and formatting to the key text.

func (*CommonWriter) WithPrefix

func (cw *CommonWriter) WithPrefix(f PrefixFunc) *CommonWriter

WithPrefix sets the prefix function for this CommonWriter. The prefix function determines what text appears before this log component.

func (*CommonWriter) WithStaticKey

func (cw *CommonWriter) WithStaticKey(key string) *CommonWriter

WithStaticKey sets a static string as the key for this CommonWriter. This is a convenience method equivalent to WithKey(Static(key)).

func (*CommonWriter) WithValueColorizer

func (cw *CommonWriter) WithValueColorizer(c Styler) *CommonWriter

WithValueColorizer sets the styler for the value portion of this CommonWriter. The value styler applies colors and formatting to the value text.

func (*CommonWriter) WithValuer

func (cw *CommonWriter) WithValuer(f Formatter) *CommonWriter

WithValuer sets the value formatter for this CommonWriter. The value formatter extracts and formats the actual value from RecordData.

func (*CommonWriter) Write

func (cw *CommonWriter) Write(info RecordData)

type EntryWriter

type EntryWriter interface {
	// Key returns the key to be used for this entry.
	//
	// If colored, this should also include the ANSI color codes
	// as length of key
	KeyLen(info RecordData) int

	// Write writes the entry to the given buffer to [RecordData.Buffer] inside info.
	//
	// There are information about whether to use color format or not inside info by
	// referencing [RecordData.Color].
	//
	// To respect it or not is up to the implementation.
	Write(info RecordData)
}

EntryWriter is the interface for components that write parts of log entries. Each EntryWriter is responsible for formatting and outputting a specific component of the log entry (e.g., level, message, timestamp).

type FileLineWriter

type FileLineWriter struct {
	*CommonWriter
}

FileLineWriter is a specialized entry writer for file and line number output. It extends CommonWriter with file/line specific formatting options.

func NewFileLineWriter

func NewFileLineWriter() *FileLineWriter

NewFileLineWriter creates a new FileLineWriter with short format and "File" key.

func (*FileLineWriter) WithFormat

func (fw *FileLineWriter) WithFormat(format Formatter) *FileLineWriter

WithFormat sets a custom formatter for the file and line number output. This allows complete control over how file/line information is formatted.

func (*FileLineWriter) WithLongFormat

func (fw *FileLineWriter) WithLongFormat() *FileLineWriter

WithLongFormat sets the formatter to use complete file paths.

func (*FileLineWriter) WithShortFormat

func (fw *FileLineWriter) WithShortFormat() *FileLineWriter

WithShortFormat sets the formatter to use short file paths with working directory trimmed.

func (*FileLineWriter) Write added in v0.1.9

func (fw *FileLineWriter) Write(info RecordData)

type Formatter

type Formatter func(info RecordData) string

Formatter is a function type that extracts and formats information from a RecordData. Formatters are used by writers to generate the string representation of log components.

func Static

func Static(key string) Formatter

Static returns a Formatter that always returns the same static string, regardless of the RecordData content.

type FunctionWriter

type FunctionWriter struct {
	*CommonWriter
}

FunctionWriter is a specialized entry writer for function name output. It extends CommonWriter with function-specific formatting options.

Example

ExampleFunctionWriter demonstrates function name formatting options.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	// Short function names (package prefix trimmed)
	functionWriterShort := prettylog.NewFunctionWriter().WithShort(true)
	handler1 := prettylog.New(
		prettylog.WithPackageName("myapp"),
		prettylog.ReplaceWriter(prettylog.DefaultFunctionWrtier, functionWriterShort),
	)

	// Full function names
	functionWriterFull := prettylog.NewFunctionWriter().WithShort(false)
	handler2 := prettylog.New(
		prettylog.ReplaceWriter(prettylog.DefaultFunctionWrtier, functionWriterFull),
	)

	logger1 := slog.New(handler1)
	logger2 := slog.New(handler2)

	logger1.Info("Short function name")
	logger2.Info("Full function name")
}

func NewFunctionWriter

func NewFunctionWriter() *FunctionWriter

NewFunctionWriter creates a new FunctionWriter with short format and "Function" key.

func (*FunctionWriter) WithFormat

func (fw *FunctionWriter) WithFormat(format Formatter) *FunctionWriter

WithFormat sets a custom formatter for the function name output. This allows complete control over how function names are formatted.

func (*FunctionWriter) WithShort

func (fw *FunctionWriter) WithShort(short bool) *FunctionWriter

WithShort sets whether to use the short function name if possible.

If true, the package name is stripped from the function name if it matches the package name given by WithPackageName option in New or Handler.Clone.

func (FunctionWriter) Write

func (fu FunctionWriter) Write(info RecordData)

type Handler

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

Handler is a slog.Handler that provides cutomizeable, modular logging capabilities.

Handler only implements the slog.Handler interface and pass the actual writing to a list of [EntryWriter]s. This allows for flexible and modular logging behavior.

func New

func New(opts ...Option) *Handler

New creates a new Handler with default configuration and applies the given options.

Default configuration:

  • Output to stderr
  • Info level logging
  • Source information enabled
  • Color support auto-detected based on terminal capabilities
  • All default writers enabled

The handler can be customized using Option functions.

Example

ExampleNew demonstrates basic usage of prettylog with default settings.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	// Create a handler with default settings
	handler := prettylog.New()
	logger := slog.New(handler)

	// Log some messages
	logger.Info("Application started", "version", "1.0.0")
	logger.Warn("This is a warning", "component", "auth")
	logger.Error("Something went wrong", "error", "connection timeout")

	// Output will be colorized and formatted with default writers
}
Example (CustomWriter)

ExampleNew_customWriter demonstrates creating and using custom entry writers.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	// Create a custom writer for request IDs
	requestIDWriter := prettylog.NewCommonWriter(func(info prettylog.RecordData) string {
		// Extract request ID from log record attributes
		info.Record.Attrs(func(a slog.Attr) bool {
			if a.Key == "request_id" {
				return false // Stop iteration, we found it
			}
			return true // Continue iteration
		})
		return "" // Would return the actual request ID in practice
	}).WithStaticKey("RequestID").WithValueColorizer(prettylog.PlainStyler)

	handler := prettylog.New(
		prettylog.WithAdditionalWriters(requestIDWriter),
	)

	logger := slog.New(handler)
	logger.Info("Request processed", "request_id", "abc-123", "duration_ms", 42)
}
Example (Customized)

ExampleNew_customized demonstrates advanced configuration options.

package main

import (
	"log/slog"
	"os"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	handler := prettylog.New(
		prettylog.WithPackageName("myapp"),
		prettylog.WithLevel(slog.LevelDebug),
		prettylog.WithOutput(os.Stdout),
	)

	logger := slog.New(handler)
	logger.Debug("Debug message with custom formatting")
	logger.Info("Info message", "user_id", 12345, "action", "login")
}

func (*Handler) Clone

func (handler *Handler) Clone(opts ...Option) *Handler

Clone makes a copy of the handler and applies the given options to it.

Attrs and Groups collected from [WithAttrs] and [WithGroup] are copied and detached from the original handler.

Other fields (like output WriteLocker) are shallow copied and may still reference the same underlying values. If you want to change those fields, use the appropriate options when calling Clone.

Example

ExampleHandler_Clone demonstrates cloning handlers with modifications.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	// Create base handler
	baseHandler := prettylog.New(
		prettylog.WithPackageName("myapp"),
		prettylog.WithLevel(slog.LevelInfo),
	)

	// Clone for debug logging with additional options
	debugHandler := baseHandler.Clone(
		prettylog.WithLevel(slog.LevelDebug),
	)

	baseLogger := slog.New(baseHandler)
	debugLogger := slog.New(debugHandler)

	baseLogger.Info("Base logger message")
	debugLogger.Debug("Debug logger message") // This will be shown due to debug level
}

func (*Handler) Enabled

func (h *Handler) Enabled(ctx context.Context, lvl slog.Level) bool

Enabled implements slog.Handler interface.

func (*Handler) Handle

func (ha *Handler) Handle(ctx context.Context, rec slog.Record) error

Handle implements slog.Handler interface.

func (*Handler) WithAttrs

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

WithAttrs implements slog.Handler interface.

func (*Handler) WithGroup

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

WithGroup implements slog.Handler interface.

type Option

type Option func(h *Handler)

Option is a function type for configuring Handler instances. Options are applied during Handler creation or cloning.

func AddWritersAfter

func AddWritersAfter(tgt EntryWriter, writers ...EntryWriter) Option

AddWritersAfter add writers after given tgt and add the writer after the tgt, unshifting the rest of the writers.

If not found or tgt is nil, the writers are appended to the end.

func AddWritersBefore

func AddWritersBefore(tgt EntryWriter, writers ...EntryWriter) Option

AddWritersBefore add writers before given tgt and unshift tgt up if found.

If not found or tgt is nil, the writers are appended to the end.

func ReplaceWriter

func ReplaceWriter(oldWriter, newWriter EntryWriter) Option

ReplaceWriter replaces an existing writer with a new one by comparing function pointers. If the old writer is not found, the new writer is appended to the list.

func WithAddSource

func WithAddSource(addSource bool) Option

WithAddSource enables or disables source information (file, line, function) in log output.

func WithAdditionalWriters

func WithAdditionalWriters(writers ...EntryWriter) Option

WithAdditionalWriters adds new entry writers to the existing list. The new writers are appended to the current writer list.

func WithColor

func WithColor(enabled bool) Option

WithColor enables or disables colored output.

func WithHandlerOptions

func WithHandlerOptions(opts *slog.HandlerOptions) Option

WithHandlerOptions sets the complete slog.HandlerOptions for the handler.

func WithLevel

func WithLevel(level slog.Level) Option

WithLevel sets the minimum log level for the handler.

func WithOutput

func WithOutput(w io.Writer) Option

WithOutput sets the output writer for the handler. The writer will be wrapped with WriteLocker if it doesn't already implement it.

func WithPackageName

func WithPackageName(name string) Option

WithPackageName supplies the Handler with the package name to be used. The package name is used by function formatters to trim package prefixes from function names, providing cleaner output.

func WithPoolSize

func WithPoolSize(maxSize int) Option

WithPoolSize sets the maximum memory buffer storage for the internal buffer pool. This controls how much memory the handler will use for buffering log output.

func WithReplaceAttr

func WithReplaceAttr(replaceAttr func(groups []string, a slog.Attr) slog.Attr) Option

WithReplaceAttr sets a function to replace or modify attributes before logging.

func WithWriters

func WithWriters(writers ...EntryWriter) Option

WithWriters sets the complete list of entry writers for the handler. This replaces all existing writers.

Example

ExampleWithWriters demonstrates replacing the default writers entirely.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	// Create custom writers
	levelWriter := prettylog.NewCommonWriter(prettylog.DefaultLevelValuer).
		WithStaticKey("LEVEL").
		WithValueColorizer(prettylog.SimpleColoredStyler)

	messageWriter := prettylog.NewCommonWriter(prettylog.DefaultMessageValuer).
		WithValueColorizer(prettylog.PlainStyler)

	handler := prettylog.New(
		prettylog.WithWriters(levelWriter, messageWriter),
	)

	logger := slog.New(handler)
	logger.Info("Custom writer configuration")
}

func WithoutWriters

func WithoutWriters(writers ...EntryWriter) Option

WithoutWriters removes writers from the handler by comparing function pointers. This is useful for removing specific default writers while keeping others.

Example

ExampleWithoutWriters demonstrates removing specific default writers.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	handler := prettylog.New(
		// Remove time and function writers, keep others
		prettylog.WithoutWriters(
			prettylog.DefaultTimeWriter,
			prettylog.DefaultFunctionWrtier,
		),
	)

	logger := slog.New(handler)
	logger.Info("No timestamp or function info", "data", "important")
}

type PrefixFunc

type PrefixFunc func(info RecordData, this *CommonWriter) string

PrefixFunc is a function type for generating prefixes between log entry components.

type PrettyJSONWriter

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

PrettyJSONWriter is a specialized entry writer for pretty-printed JSON output. It formats log attributes as colored, indented JSON, excluding standard slog keys.

It excludes standard slog keys (time, level, message, source) and formats the remaining attributes as colored JSON.

Example

ExamplePrettyJSONWriter demonstrates structured data formatting.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	handler := prettylog.New()
	logger := slog.New(handler)

	// Log with structured data - will be pretty-printed as JSON
	logger.Info("User action",
		"user", slog.GroupValue(
			slog.String("id", "12345"),
			slog.String("name", "John Doe"),
			slog.String("email", "john@example.com"),
		),
		"action", "login",
		"metadata", slog.GroupValue(
			slog.String("ip", "192.168.1.1"),
			slog.String("user_agent", "Mozilla/5.0..."),
			slog.Int("session_duration", 3600),
		),
	)
}

func NewPrettyJSONWriter

func NewPrettyJSONWriter() *PrettyJSONWriter

NewPrettyJSONWriter creates a new PrettyJSONWriter with default pretty-printing options and terminal styling.

func (*PrettyJSONWriter) KeyLen

func (pr *PrettyJSONWriter) KeyLen(info RecordData) int

KeyLen implements EntryWriter interface. Always returns 0.

func (*PrettyJSONWriter) WithPrettyOptions

func (pr *PrettyJSONWriter) WithPrettyOptions(opts *pretty.Options) *PrettyJSONWriter

WithPrettyOptions sets the pretty-printing options for JSON formatting. This controls indentation, sorting, and other formatting aspects.

func (*PrettyJSONWriter) WithStyle

func (pr *PrettyJSONWriter) WithStyle(style *pretty.Style) *PrettyJSONWriter

WithStyle sets the color styling for JSON output. This controls the colors used for different JSON elements like keys, values, etc.

func (*PrettyJSONWriter) Write

func (pr *PrettyJSONWriter) Write(info RecordData)

Write implements EntryWriter interface.

type RecordData

type RecordData struct {
	// Context is the context passed to the [slog.Handler.Handle] method.
	Context context.Context
	// Record is the current [slog.Record] being processed.
	//
	// Do note that [Formatter]s and [Styler]s are called for every
	// log record. It is in your best interest to minimize calling potentially
	// expensive operations like [slog.Record.Attrs] or [slog.Record.Clone].
	Record slog.Record
	// PackageName is the name of the package given by setting [WithPackageName] option
	// on [New] or [Handler.Clone].
	PackageName string
	// Frame is the runtime.Frame information about the caller.
	//
	// It's cached here to avoid multiple calls to [runtime.CallerFrames] or [runtime.FuncForPC] inside formatters and stylers.
	//
	// Do note that if [runtime.Frame.Func] is nil, it means that the function information is not available. Ensure to take note of that into account when using it.
	Frame runtime.Frame

	// Color indicates if output should be colored or not.
	//
	// If false, it means the text output must not have ANSI color codes.
	Color bool

	// KeyFieldLength is the length of the longest key field from all the [EntryWriter] after
	// including ANSI color codes.
	//
	// This value is zero when passed into [EntryWriter.KeyLen] (because it is not known yet).
	KeyFieldLength int

	// HandlerOptions is the handler options passed to the handler.
	//
	// This field may be nil and it's members can also be nil.
	HandlerOptions *slog.HandlerOptions

	// Buffer is a buffer that can be used by [EntryWriter]s to write
	// data to.
	//
	// The Buffer is shared between all registered [EntryWriter]s, so
	// you can peek into what previous writers have written. To avoid
	// unwanted log output, avoid calling methods that move the internal
	// cursor backwards like [bytes.Buffer.Reset], [bytes.Buffer.Truncate],
	// or Unread methods outside what is strictly necessary.
	//
	// Do not hold references to this buffer outside the scope as
	// the buffer will be reused for future log records.
	//
	// If you have to keep hold of the value, make a copy of the buffer
	Buffer *bytes.Buffer
}

RecordData contains contextual information about the current log record being processed. It is passed to formatters, stylers, and entry writers to provide all necessary context for generating the final log output.

type Styler

type Styler func(info RecordData, formatted string) (styled string)

Styler is a function type that applies styling (colors, formatting) to formatted strings. It receives the RecordData for context (like log level) and the formatted string, returning the styled version.

type TimeWriter

type TimeWriter struct {
	*CommonWriter
}

TimeWriter is a specialized entry writer for timestamp output. It extends CommonWriter with time-specific formatting options.

Example

ExampleTimeWriter demonstrates custom time writer configuration.

package main

import (
	"log/slog"

	"github.com/tigorlazuardi/prettylog"
)

func main() {
	// RFC3339 format
	timeWriterRFC3339 := prettylog.NewTimeWriter().WithRFC3339Format()
	handler1 := prettylog.New(
		prettylog.ReplaceWriter(prettylog.DefaultTimeWriter, timeWriterRFC3339),
	)

	// Custom format
	timeWriterCustom := prettylog.NewTimeWriter().WithTimeFormat("2006-01-02 15:04:05")
	handler2 := prettylog.New(
		prettylog.ReplaceWriter(prettylog.DefaultTimeWriter, timeWriterCustom),
	)

	// Time-only format (default)
	timeWriterOnly := prettylog.NewTimeWriter().WithTimeOnlyFormat()
	handler3 := prettylog.New(
		prettylog.ReplaceWriter(prettylog.DefaultTimeWriter, timeWriterOnly),
	)

	logger1 := slog.New(handler1)
	logger2 := slog.New(handler2)
	logger3 := slog.New(handler3)

	logger1.Info("RFC3339 timestamp")
	logger2.Info("Custom timestamp format")
	logger3.Info("Time-only timestamp")
}

func NewTimeWriter

func NewTimeWriter() *TimeWriter

NewTimeWriter creates a new TimeWriter with time-only format and "Time" key.

func (*TimeWriter) WithRFC3339Format

func (tw *TimeWriter) WithRFC3339Format() *TimeWriter

WithRFC3339Format sets the time formatter to use RFC3339 format.

func (*TimeWriter) WithTimeFormat

func (tw *TimeWriter) WithTimeFormat(layout string) *TimeWriter

WithTimeFormat sets the time formatter to use a custom time layout. The layout parameter follows Go's time formatting conventions.

func (*TimeWriter) WithTimeOnlyFormat

func (tw *TimeWriter) WithTimeOnlyFormat() *TimeWriter

WithTimeOnlyFormat sets the time formatter to use time.TimeOnly format ("15:04:05").

func (*TimeWriter) Write

func (tw *TimeWriter) Write(info RecordData)

type UnimplementedEntryWriter

type UnimplementedEntryWriter struct{}

UnimplementedEntryWriter is an EntryWriter that does nothing. It can be embedded to have forward compatible implementations.

func (UnimplementedEntryWriter) KeyLen

func (UnimplementedEntryWriter) Write

type WriteLocker

type WriteLocker interface {
	io.Writer
	sync.Locker
}

WriteLocker combines io.Writer with sync.Locker for thread-safe writing. This interface ensures that write operations can be synchronized across multiple goroutines.

func WrapWriteLocker

func WrapWriteLocker(w io.Writer) WriteLocker

WrapWriteLocker wraps an io.Writer to implement the WriteLocker interface. If the writer already implements WriteLocker, it returns the writer unchanged. Otherwise, it wraps it with a mutex for thread-safe writing.

Jump to

Keyboard shortcuts

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