formatter

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PlaceholderTimestamp = "{{timestamp}}"
	PlaceholderLevel     = "{{level}}"
	PlaceholderLogger    = "{{logger}}"
	PlaceholderMessage   = "{{message}}"
	PlaceholderCaller    = "{{caller}}"
	PlaceholderFields    = "{{fields}}"
	PlaceholderSource    = "{{source}}"
	PlaceholderTraceID   = "{{trace_id}}"
	PlaceholderSpanID    = "{{span_id}}"
	// Runtime fields
	PlaceholderHostname  = "{{hostname}}"
	PlaceholderPID       = "{{pid}}"
	PlaceholderGoroutine = "{{goroutine}}"
	PlaceholderEnv       = "{{env}}"
)

Supported placeholders

View Source
const (
	LevelDebug = logcastle.LevelDebug
	LevelInfo  = logcastle.LevelInfo
	LevelWarn  = logcastle.LevelWarn
	LevelError = logcastle.LevelError
	LevelFatal = logcastle.LevelFatal
)

Variables

ValidPlaceholders lists all valid placeholders

Functions

func GetRuntimeFields

func GetRuntimeFields() map[string]interface{}

GetRuntimeFields returns current runtime information as a map. Includes hostname, PID, environment, goroutine count, and custom env fields.

func InitRuntimeFields

func InitRuntimeFields(environment string, customEnvFields map[string]string)

InitRuntimeFields initializes global runtime context for all logs. Call once at app startup. environment: "prod"/"dev"/etc, customEnvFields: datacenter, region, etc.

func ValidateTemplate

func ValidateTemplate(template string) error

ValidateTemplate validates a template string Checks for: - Required placeholder presence (at least timestamp and message) - Invalid placeholder syntax - Unknown placeholders

Types

type CustomLogEntry

type CustomLogEntry struct {
	Timestamp time.Time
	Level     string
	Logger    string
	Message   string
	Caller    string
	Fields    map[string]interface{}
	TraceID   string
	SpanID    string
	Source    string
}

CustomLogEntry represents a log entry for JSON custom formatter

type CustomTemplate

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

CustomTemplate represents a compiled custom log format template

func CompileTemplate

func CompileTemplate(template string) (*CustomTemplate, error)

CompileTemplate compiles a custom template string into an executable template Returns an error if the template contains invalid placeholders or syntax

func (*CustomTemplate) Execute

func (ct *CustomTemplate) Execute(entry *LogEntry) string

Execute executes the template with the given log entry

type Format

type Format string

Format represents the output format for logs

const (
	JSON   Format = "json"
	Text   Format = "text"
	LogFmt Format = "logfmt"
	Custom Format = "custom"
)

type Formatter

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

Formatter formats log entries to the desired output format

func NewCustomFormatter

func NewCustomFormatter(template string) (*Formatter, error)

NewCustomFormatter creates a formatter with a custom template The template is validated at creation time

func NewFormatter

func NewFormatter(format Format) *Formatter

NewFormatter creates a new formatter with the specified format

func NewFormatterWithTimestamp

func NewFormatterWithTimestamp(format Format, tsFormat TimestampFormat, customTsFormat string) *Formatter

NewFormatterWithTimestamp creates a formatter with custom timestamp format

func (*Formatter) Format

func (f *Formatter) Format(entry *LogEntry) []byte

Format formats a log entry according to the configured format

type JSONFormatter

type JSONFormatter struct {
	// FieldOrder specifies the order of fields in JSON output for readability.
	// Empty = default alphabetical. Example: ["timestamp", "level", "message"]
	FieldOrder []string

	// GlobalFields are automatically added to every log entry.
	// Use for service name, version, region, etc. Thread-safe updates via SetGlobalField.
	GlobalFields map[string]interface{}

	// IncludeRuntimeFields adds hostname, PID, etc. to logs
	IncludeRuntimeFields bool

	// TimestampFormat for formatting timestamps
	TimestampFormat string

	// PrettyPrint enables indented JSON output
	PrettyPrint bool
	// contains filtered or unexported fields
}

JSONFormatter provides customizable JSON formatting with global fields and field ordering. Thread-safe. Supports runtime fields, custom field order, and pretty printing.

func NewJSONFormatter

func NewJSONFormatter() *JSONFormatter

NewJSONFormatter creates a JSON formatter with sensible defaults. Default field order: timestamp, level, message. Call SetGlobalField to add metadata.

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(entry *CustomLogEntry) []byte

Format formats a log entry as customizable JSON with global and runtime fields. Returns newline-terminated JSON bytes. Honors FieldOrder if set.

func (*JSONFormatter) RemoveGlobalField

func (f *JSONFormatter) RemoveGlobalField(key string)

RemoveGlobalField removes a global field

func (*JSONFormatter) SetGlobalField

func (f *JSONFormatter) SetGlobalField(key string, value interface{})

SetGlobalField adds or updates a global field that appears in all logs. Thread-safe. Example: f.SetGlobalField("service", "api-gateway")

func (*JSONFormatter) SetGlobalFields

func (f *JSONFormatter) SetGlobalFields(fields map[string]interface{})

SetGlobalFields sets multiple global fields at once

type Level

type Level = logcastle.Level

type LogEntry

type LogEntry = logcastle.LogEntry

Type aliases for convenience

type RuntimeFields

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

RuntimeFields provides access to runtime and environment information for log enrichment. Collects hostname, PID, environment name, and custom fields once at startup.

type TimestampFormat

type TimestampFormat string

TimestampFormat represents timestamp formatting options

const (
	TimestampFormatRFC3339Nano   TimestampFormat = "rfc3339nano"
	TimestampFormatRFC3339       TimestampFormat = "rfc3339"
	TimestampFormatRFC3339Millis TimestampFormat = "rfc3339milli"
	TimestampFormatUnix          TimestampFormat = "unix"
	TimestampFormatUnixMilli     TimestampFormat = "unixmilli"
	TimestampFormatUnixNano      TimestampFormat = "unixnano"
	TimestampFormatDateTime      TimestampFormat = "datetime"
	TimestampFormatCustom        TimestampFormat = "custom"
)

Jump to

Keyboard shortcuts

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