Documentation
¶
Overview ¶
Package logcastle provides high-performance centralized log orchestration. It intercepts logs from any library, standardizes the format, and writes to configured outputs.
Basic Usage:
import "github.com/bhaskarblur/go-logcastle"
func main() {
logcastle.Init(logcastle.Config{
Format: logcastle.JSON, // or Text, LogFmt
Level: logcastle.LevelInfo,
})
defer logcastle.Close()
// All logs now intercepted and standardized
log.Println("Server started")
fmt.Println("Processing request")
}
Formatting Examples:
1. Development Mode (Pretty + Readable):
logcastle.Config{
Format: logcastle.JSON,
PrettyPrint: true, // Multi-line JSON
FlattenFields: true, // Clean structure
}
2. Production Grafana/Loki (Optimized for Label Extraction):
logcastle.Config{
Format: logcastle.JSON,
FlattenFields: true, // CRITICAL: Fields at root for Loki labels
PrettyPrint: false, // Single-line for log aggregation
FieldOrder: []string{"timestamp", "level", "service", "env"},
}
3. Terminal Output with Colors:
logcastle.Config{
Format: logcastle.Text, // Human-readable
ColorOutput: true, // ERROR=red, WARN=yellow, INFO=green
}
4. ELK/Logstash (Custom Field Ordering):
logcastle.Config{
Format: logcastle.JSON,
FlattenFields: true,
FieldOrder: []string{"timestamp", "level", "service", "message"},
}
Format Types:
- JSON (default): {"timestamp":"2026-03-23T10:00:00Z","level":"info","message":"server started"}
- Text: 2026-03-23T10:00:00Z INFO server started
- LogFmt: time=2026-03-23T10:00:00Z level=info msg="server started"
Formatting Options:
- FlattenFields (default: true): Merge enrichment fields to root level
- PrettyPrint (default: false): Multi-line JSON with indentation
- ColorOutput (default: false): ANSI colors for Text format
- FieldOrder (default: nil): Custom field ordering in JSON
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Close ¶
func Close() error
Close gracefully shuts down the log castle and flushes buffered logs. Always call this before application exit (use defer).
func Init ¶
Init initializes the log castle with the given config. Call this once at startup. All fmt.Print*, log.Print*, etc. will be intercepted. Returns error if initialization fails (e.g., invalid config).
Types ¶
type BufferedWriter ¶
type BufferedWriter struct {
// contains filtered or unexported fields
}
BufferedWriter batches log writes for improved performance. Automatically flushes based on buffer size and time interval.
func NewBufferedWriter ¶
func NewBufferedWriter(output io.Writer, bufferSize int, flushInterval time.Duration) *BufferedWriter
NewBufferedWriter creates a buffered writer with specified capacity and flush interval. bufferSize: max entries before auto-flush. flushInterval: time between flushes.
func (*BufferedWriter) Flush ¶
func (w *BufferedWriter) Flush() error
Flush writes all buffered data
func (*BufferedWriter) Start ¶
func (w *BufferedWriter) Start()
Start begins the auto-flush goroutine for periodic flushing. Called automatically by Init. Don't call manually.
func (*BufferedWriter) Stop ¶
func (w *BufferedWriter) Stop() error
Stop stops the writer and flushes remaining data to output. Idempotent - safe to call multiple times. Returns error if flush fails.
func (*BufferedWriter) Write ¶
func (w *BufferedWriter) Write(data []byte) error
Write adds data to the buffer
type Castle ¶
type Castle struct {
// contains filtered or unexported fields
}
Castle is the main log orchestrator
type Config ¶
type Config struct {
// Format specifies the output format: JSON (default, structured), Text (readable), or LogFmt (key=value).
//
// JSON example: {\"timestamp\":\"2026-03-23T10:00:00Z\",\"level\":\"info\",\"message\":\"server started\"}
// Text example: 2026-03-23T10:00:00Z INFO server started
// LogFmt example: time=2026-03-23T10:00:00Z level=info msg=\"server started\"
//
// Default: JSON
Format Format
// Level sets the minimum log level to capture (Debug, Info, Warn, Error, Fatal).
// Logs below this level are filtered out.
Level Level
// Output is where to write standardized logs (default: os.Stdout)
Output io.Writer
// BufferSize controls internal buffering (default: 10000).
// Increase for high throughput, decrease for low latency.
BufferSize int
// FlushInterval is how often to flush buffered logs
FlushInterval time.Duration
// EnrichFields adds additional fields to all logs
EnrichFields map[string]interface{}
// TimestampFormat specifies how timestamps are formatted in output.
// Default: RFC3339Nano. See TimestampFormat constants for options.
TimestampFormat TimestampFormat
// CustomTimestampFormat is used when TimestampFormat is TimestampFormatCustom
// Uses Go time format layout (e.g., "2006-01-02 15:04:05")
CustomTimestampFormat string
// IncludeLoggerField controls whether to include the 'logger' field in output.
// When false, the logger field is omitted from formatted logs (default: false)
IncludeLoggerField bool
// IncludeParseError controls whether to include 'log_parse_error' field in output.
// When false, parse error messages are omitted from formatted logs (default: false)
IncludeParseError bool
// FlattenFields merges EnrichFields to root level instead of nested "fields" object.
// This is CRITICAL for Grafana/Loki label extraction and readability.
//
// When true (default):
// {"timestamp":"...","level":"info","env":"prod","service":"api"}
//
// When false:
// {"timestamp":"...","level":"info","fields":{"env":"prod","service":"api"}}
//
// Default: true (recommended for production observability)
FlattenFields bool
// PrettyPrint formats JSON with indentation for terminal viewing and debugging.
// Use true for development/debugging, false for production log aggregation.
//
// When true:
// {
// "timestamp": "2026-03-23T10:00:00Z",
// "level": "info",
// "message": "server started"
// }
//
// When false (default):
// {"timestamp":"2026-03-23T10:00:00Z","level":"info","message":"server started"}
//
// Default: false (single-line for production)
PrettyPrint bool
// ColorOutput adds ANSI color codes to terminal output (Text format only, ignored in JSON).
// Improves visual distinction between log levels in terminal/console.
//
// When true (Text format):
// ERROR appears in bold red
// WARN appears in yellow
// INFO appears in green
// DEBUG appears in gray
//
// Example output:
// 2026-03-23T10:00:00Z \033[32mINFO\033[0m server started
//
// Default: false (no colors)
ColorOutput bool
// FieldOrder specifies which fields appear first in JSON output.
// Useful for optimizing log readability in ELK/Logstash/Splunk where field order matters.
//
// Example for ELK/Logstash:
// FieldOrder: []string{"timestamp", "level", "service", "env", "message"}
//
// Output:
// {"timestamp":"...","level":"info","service":"api","env":"prod","message":"...","caller":"..."}
//
// Fields not in FieldOrder appear after, in alphabetical order.
// Default: nil (standard order: timestamp, level, message, then others)
FieldOrder []string
}
Config configures the log castle behavior and output. Set Format, Level, Output destination, and other options to customize logging.
Quick Start - Use defaults:
logcastle.Init(logcastle.DefaultConfig())
Custom Configuration:
logcastle.Init(logcastle.Config{
Format: logcastle.JSON, // or Text, LogFmt
Level: logcastle.LevelInfo,
EnrichFields: map[string]interface{}{
"service": "api-server",
"env": "production",
},
})
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults for most applications.
Defaults:
- Format: JSON (structured logs)
- Level: LevelInfo (filters out debug logs)
- Output: os.Stdout (standard output)
- BufferSize: 10000 (high throughput)
- FlushInterval: 100ms (balance between latency and performance)
- FlattenFields: true (Grafana/Loki optimized)
- PrettyPrint: false (single-line for production)
- ColorOutput: false (no ANSI codes)
- IncludeLoggerField: false (clean output)
- IncludeParseError: false (clean output)
Example usage:
config := logcastle.DefaultConfig()
config.Level = logcastle.LevelDebug
config.EnrichFields = map[string]interface{}{
"service": "api-server",
"env": "production",
}
logcastle.Init(config)
type Format ¶
type Format string
Format represents the output format for logs. Three formats are available:
JSON (default): Structured JSON format for production and log aggregators.
Example: {"timestamp":"2026-03-23T10:00:00Z","level":"info","message":"server started"}
Text: Human-readable format for terminal viewing and development.
Example: 2026-03-23T10:00:00Z INFO server started
LogFmt: Key=value pairs format compatible with Logstash and other parsers.
Example: time=2026-03-23T10:00:00Z level=info msg="server started"
const ( // JSON is the default format - structured, machine-readable, ideal for Grafana/Loki/ELK JSON Format = "json" // Text is human-readable format with optional ANSI colors for terminal output Text Format = "text" // LogFmt is key=value format compatible with Heroku/Splunk/Logstash LogFmt Format = "logfmt" )
type Formatter ¶
type Formatter struct {
// contains filtered or unexported fields
}
Formatter formats log entries to the desired output format (JSON, Text, LogFmt). Supports custom timestamp formats, field flattening, pretty printing, and color output.
Format Options:
- JSON: {"timestamp":"...","level":"info","message":"..."}
- Text: 2026-03-23T10:00:00Z INFO server started
- LogFmt: time=2026-03-23T10:00:00Z level=info msg="server started"
Advanced Features:
- FlattenFields: Merge enrichment fields to root (Grafana/Loki optimization)
- PrettyPrint: Multi-line JSON with indentation (development/debugging)
- ColorOutput: ANSI colors for Text format (terminal readability)
- FieldOrder: Custom field ordering in JSON (ELK/Logstash optimization)
type LogEntry ¶
type LogEntry struct {
// Timestamp is when the log was created.
Timestamp time.Time `json:"timestamp"`
Level Level `json:"level"`
Logger string `json:"logger"`
Message string `json:"message"`
Caller string `json:"caller,omitempty"`
Fields map[string]interface{} `json:"fields,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
Source string `json:"-"` // Internal use only
// ParseError indicates if log parsing failed (e.g., malformed JSON, unstructured text).
ParseError string `json:"log_parse_error,omitempty"`
}
LogEntry represents a parsed and standardized log entry from any logging library. All logs are normalized into this structure for consistent processing.
func NewLogEntry ¶
func NewLogEntry() *LogEntry
NewLogEntry creates a new log entry with default values. Used internally by parsers to initialize log entries.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser detects and parses logs from multiple formats (JSON, Logrus, Zap, etc.). Automatically identifies format and extracts structured data.
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner is a high-performance line scanner
func NewScanner ¶
NewScanner creates a scanner with optimized buffer size for log processing. Supports lines up to 1MB (MaxScanTokenSize).
type TimestampFormat ¶
type TimestampFormat string
TimestampFormat represents the format for timestamps in log entries. Choose from RFC3339, Unix epoch, or custom formats for flexibility.
const ( // TimestampFormatRFC3339Nano is the default format with nanosecond precision TimestampFormatRFC3339Nano TimestampFormat = "rfc3339nano" // TimestampFormatRFC3339 is standard RFC3339 TimestampFormatRFC3339 TimestampFormat = "rfc3339" // TimestampFormatRFC3339Millis includes millisecond precision TimestampFormatRFC3339Millis TimestampFormat = "rfc3339milli" // TimestampFormatUnix is Unix timestamp (seconds) TimestampFormatUnix TimestampFormat = "unix" // TimestampFormatUnixMilli is Unix timestamp in milliseconds TimestampFormatUnixMilli TimestampFormat = "unixmilli" // TimestampFormatUnixNano is Unix timestamp in nanoseconds TimestampFormatUnixNano TimestampFormat = "unixnano" // TimestampFormatDateTime is human-readable format TimestampFormatDateTime TimestampFormat = "datetime" // TimestampFormatCustom allows custom format string TimestampFormatCustom TimestampFormat = "custom" )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
benchmark
command
|
|
|
fallback-parsing
command
|
|
|
formatting
command
|
|
|
json-custom
command
|
|
|
logrus
command
|
|
|
mixed
command
|
|
|
timestamp-formats
command
|
|
|
zap
command
|
|
|
internal
|
|