emit

package module
v1.2.5 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2025 License: MIT Imports: 11 Imported by: 5

README

Emit

A lightweight, structured logging library for Go applications with built-in security features and industry-leading performance. Emit provides automatic PII/sensitive data masking while outperforming all major logging libraries.

 

Go Reference Go Tests Go Report Card GitHub Tag License

 

  • Automatic data protection - PII and sensitive data masked by default
  • Elegant API - emit.Info.Msg() for simplicity, emit.Info.Field() for structure

 

Why Choose Emit?

Clean, Simple API
// Payment logging with built-in PCI DSS compliance
emit.Info.Field("Payment processed",
    emit.NewFields().
        String("transaction_id", "txn_abc123").
        String("card_number", "4111-1111-1111-1111").   // Auto-masked
        String("cardholder", "John Doe").               // Auto-masked
        Float64("amount", 99.99).
        String("currency", "USD").
        Bool("success", true))

🔝 back to top

 

// Crystal clear intent - no cryptic function names
emit.Info.Field("User authenticated",
    emit.NewFields().
        String("user_id", "12345").
        String("email", "[email protected]"). // Auto-masked: "***PII***"
        Bool("success", true))

// Simple key-value pairs
emit.Error.KeyValue("Payment failed",
    "transaction_id", "txn_123",
    "amount", 99.99,
    "card_number", "4111-1111-1111-1111")    // Auto-masked: "***PII***"

🔝 back to top

 

Zero-Config Security

Automatic protection of sensitive data without any configuration:

emit.Info.Field("User registration",
    emit.NewFields().
        String("email", "[email protected]").      // → "***PII***"
        String("password", "secret123").          // → "***MASKED***"
        String("api_key", "sk-1234567890").       // → "***MASKED***"
        String("username", "john_doe").           // → "john_doe" (safe)
        Int("user_id", 12345))                    // → 12345 (safe)

🔝 back to top

 

Installation

go get github.com/cloudresty/emit

🔝 back to top

 

Quick Start

package main

import (
    "time"
    "github.com/cloudresty/emit"
)

func main() {

    // Clean, self-documenting API ✨

    // Structured logging with clear intent
    emit.Info.Field("User registration",
        emit.NewFields().
            String("email", "[email protected]").     // Auto-masked
            String("username", "john_doe").
            Int("user_id", 67890).
            Bool("newsletter", true).
            Time("created_at", time.Now()))

    // Simple key-value pairs
    emit.Error.KeyValue("Payment failed",
        "transaction_id", "txn_123",
        "amount", 29.99,
        "currency", "USD")

    // Ultra-fast structured field logging
    emit.Warn.StructuredFields("High memory usage",
        emit.ZString("service", "database"),
        emit.ZFloat64("memory_percent", 87.5))

    // Memory-pooled high-performance logging
    emit.Debug.Pool("Database operation", func(pf *emit.PooledFields) {
        pf.String("query", "SELECT * FROM users").
           Int("rows", 1234).
           Float64("duration_ms", 15.7)
    })

    // Simple messages
    emit.Info.Msg("Application started successfully")
}

 

JSON Output (Production):

{"timestamp":"2025-06-11T10:30:45.123456789Z","level":"info","message":"User registration","fields":{"email":"***PII***","username":"john_doe","user_id":67890,"newsletter":true,"created_at":"2025-06-11T10:30:45.123456789Z"}}
{"timestamp":"2025-06-11T10:30:45.124567890Z","level":"error","message":"Payment failed","fields":{"transaction_id":"txn_123","amount":29.99,"currency":"USD"}}

🔝 back to top

 

Elegant API Overview

Every logging level (Info, Error, Warn, Debug) provides the same clean, consistent interface:

// All levels support the same methods
emit.Info.Msg(msg)                           // Simple message
emit.Info.Field(msg, fields)                 // Structured fields
emit.Info.StructuredFields(msg, zfields...)  // Ultra-fast structured fields (Zap-compatible)
emit.Info.KeyValue(msg, k, v, ...)           // Key-value pairs
emit.Info.Pool(msg, func)                    // Memory-pooled performance

// Same elegant API for all levels
emit.Error.Field(msg, fields)                // Error with structured data
emit.Warn.KeyValue(msg, k, v, ...)           // Warning with key-values
emit.Debug.StructuredFields(msg, zfields...) // Debug with structured fields

🔝 back to top

 

Key Features

Built-in Security
  • Automatic PII masking - Emails, phone numbers, addresses protected by default
  • Sensitive data protection - Passwords, API keys, tokens automatically masked
  • GDPR/CCPA compliant - Built-in compliance with privacy regulations
  • Zero data leaks - Impossible to accidentally log sensitive information

 

Performance Optimized
  • 63.0 ns/op simple logging - 23% faster than Zap
  • 96.0 ns/op structured fields - 33% faster than Zap with zero allocations
  • Zero-allocation API - StructuredFields() methods achieve 0 B/op, 0 allocs/op
  • Memory pooling - Pool() methods for high-throughput scenarios

 

Developer Friendly
  • Elegant API - Clear, self-documenting method names
  • IDE-friendly - Perfect autocomplete with emit.Info. discovery
  • Zero dependencies - Uses only Go standard library
  • Environment-aware - JSON for production, plain text for development

🔝 back to top

 

Documentation

 

Complete Guides

🔝 back to top

 

Environment Configuration
# Production (secure by default)
export EMIT_FORMAT=json
export EMIT_LEVEL=info
# PII and sensitive masking enabled automatically

# Development (show data for debugging)
export EMIT_FORMAT=plain
export EMIT_LEVEL=debug
export EMIT_MASK_SENSITIVE=false
export EMIT_MASK_PII=false

🔝 back to top

 

Programmatic Setup
// Quick setup
emit.SetComponent("user-service")
emit.SetVersion("v2.1.0")
emit.SetLevel("info")

// Production mode (secure, JSON, info level)
emit.SetProductionMode()

// Development mode (show data, plain text, debug level)
emit.SetDevelopmentMode()

🔝 back to top

 

Real-World Examples

Microservice Logging
// Service initialization
emit.SetComponent("auth-service")
emit.SetVersion("v1.2.3")

// Request logging with automatic security
emit.Info.Field("API request",
    emit.NewFields().
        String("method", "POST").
        String("endpoint", "/api/login").
        String("user_email", userEmail).        // Auto-masked
        String("client_ip", clientIP).          // Auto-masked
        Int("status_code", 200).
        Duration("response_time", duration))

🔝 back to top

 

Payment Processing
// Payment logging with built-in PCI DSS compliance
emit.Info.Field("Payment processed",
    emit.NewFields().
        String("transaction_id", "txn_abc123").
        String("card_number", "4111-1111-1111-1111").  // Auto-masked
        String("cardholder", "John Doe").              // Auto-masked
        Float64("amount", 99.99).
        String("currency", "USD").
        Bool("success", true))

🔝 back to top

 

High-Performance Logging
// Ultra-fast logging for hot paths
func processRequest() {
    start := time.Now()

    // ... request processing

    emit.Debug.StructuredFields("Request processed",
        emit.ZString("endpoint", "/api/data"),
        emit.ZInt("status", 200),
        emit.ZDuration("duration", time.Since(start)))
}

🔝 back to top

 

Migration from Other Loggers

From Standard Log
// Before (UNSAFE)
log.Printf("User %s with password %s logged in", username, password)

// After (SECURE)
emit.Info.KeyValue("User logged in",
    "username", username,      // Auto-protected if PII
    "password", password)      // Auto-masked

🔝 back to top

 

From Logrus
// Before (manual security)
logrus.WithFields(logrus.Fields{
    "email": maskEmail(email),  // Manual masking required!
}).Info("User action")

// After (automatic security)
emit.Info.Field("User action",
    emit.NewFields().
        String("email", email))  // Auto-masked

🔝 back to top

 

From Zap
// Before (complex, manual security)
logger.Info("Payment",
    zap.String("email", maskPII(email)),     // Manual masking!
    zap.String("card", maskSensitive(card))) // Manual masking!

// After (simple, automatic security)
emit.Info.KeyValue("Payment processed",
    "email", email,    // Auto-masked
    "card", card)      // Auto-masked

🔝 back to top

 

Compliance & Security

Automatic Compliance
  • ✅ GDPR - EU personal data automatically protected
  • ✅ CCPA - California privacy law compliance
  • ✅ HIPAA - Healthcare data protection (with custom fields)
  • ✅ PCI DSS - Payment card data automatically masked

🔝 back to top

 

Protected Data Types

PII (Automatically Masked as ***PII***)

  • Email addresses, phone numbers, names
  • Addresses, IP addresses, credit cards
  • SSN, passport numbers, driver licenses

Sensitive Data (Automatically Masked as ***MASKED***)

  • Passwords, PINs, API keys
  • Access tokens, private keys, certificates
  • Session IDs, authorization headers

🔝 back to top

 

Why Emit is the Secure Choice

Traditional Loggers
  • ❌ Manual data protection required
  • ❌ Easy to accidentally log sensitive data
  • ❌ Complex setup for production security
  • ❌ Risk of compliance violations

 

Emit in a Nutshell
  • ✅ Automatic data protection out of the box
  • ✅ Impossible to accidentally expose PII/sensitive data
  • ✅ Zero-config security for production
  • ✅ Built-in compliance with privacy regulations
  • ✅ Elegant, developer-friendly API
  • ✅ Performance optimized for production workloads

🔝 back to top

 

Real-World Impact Summary

Security: The Hidden Cost of Traditional Loggers

When choosing a logging library, most developers focus solely on performance metrics. However, security vulnerabilities in logging are among the most common causes of data breaches in production applications:

  • Data Breach Risk: Traditional loggers like Zap and Logrus require developers to manually mask sensitive data. A single oversight can expose passwords, API keys, or PII in log files.
  • Compliance Violations: GDPR fines can reach €20M or 4% of annual revenue. CCPA violations cost up to $7,500 per record. Emit's automatic masking prevents these costly violations.
  • Developer Burden: Manual masking increases development time and introduces bugs. Emit eliminates this overhead entirely.

🔝 back to top

 

Performance: Security Without Compromise

Traditional Assumption: "Security features must sacrifice performance" Emit Reality: Built-in security with industry-leading speed

Our benchmarks demonstrate that Emit's automatic security features add zero performance overhead compared to manual implementations: Benchmark results.

Key Insight: Emit with automatic security (213 ns/op) is significantly faster than Logrus without any security protection (2,872 ns/op), and competitive with Zap's unsafe mode (171 ns/op) while providing complete data protection.

🔝 back to top

 

Production Impact: Beyond Benchmarks
Traditional Logging Workflow
  1. Write logging code
  2. Manually identify sensitive fields
  3. Implement custom masking functions
  4. Review code for security issues
  5. Test masking implementations
  6. Monitor for data leaks in production
  7. Risk: One missed field = potential breach

🔝 back to top

 

Emit Workflow
  1. Write logging code
  2. Done - Security is automatic and guaranteed

🔝 back to top

 

Cost Analysis

Medium-sized application (10 developers, 2-year development cycle):

Traditional Loggers:
- Security implementation time: 40 hours/developer = 400 hours
- Security review overhead: 20% of logging code reviews = 80 hours
- Bug fixes for missed masking: 20 hours
- Total: 500 hours × $150/hour = $75,000

Emit:
- Security implementation time: 0 hours (automatic)
- Security review overhead: 0 hours (automatic)
- Bug fixes: 0 hours (impossible to leak data)
- Total: $0

ROI: $75,000 saved + zero breach risk

🔝 back to top

 

When to Choose Each Approach

Choose Emit when:

  • Building production applications with sensitive data
  • Compliance requirements (GDPR, CCPA, HIPAA, PCI DSS)
  • Team includes junior developers
  • Performance is critical
  • Development speed matters

Choose traditional loggers when:

  • Working with completely non-sensitive data
  • You have dedicated security experts on your team
  • You enjoy implementing custom security solutions
  • Vendor lock-in concerns outweigh security benefits

Bottom Line: Emit delivers the security of enterprise logging solutions with the performance of the fastest libraries and the simplicity of modern APIs.

🔝 back to top

 

Get Started

  1. Install: go get github.com/cloudresty/emit
  2. Basic usage: emit.Info.Msg("Hello, secure world!")
  3. Add structure: emit.Info.KeyValue("User action", "user_id", 123)
  4. Go advanced: emit.Info.Field("Complex event", emit.NewFields()...)
  5. Optimize performance: emit.Info.StructuredFields("Hot path", emit.ZString(...))

Choose emit for secure, compliant, and elegant logging in your Go applications.

🔝 back to top

 

Performance Breakthrough: Zero-Allocation Structured Fields

Emit achieves what was previously thought impossible in Go logging - zero heap allocations for structured field logging while maintaining full compatibility with Zap-style APIs.

// Zero-allocation structured logging (Zap-compatible API)
emit.Info.StructuredFields("User action",          // 96 ns/op, 0 B/op, 0 allocs/op
    emit.ZString("user_id", "12345"),
    emit.ZString("action", "login"),
    emit.ZString("email", "[email protected]"),      // → "***MASKED***" (automatic)
    emit.ZBool("success", true))

// Compare with Zap (requires heap allocations)
zapLogger.Info("User action",                      // 143 ns/op, 259 B/op, 1 allocs/op
    zap.String("user_id", "12345"),
    zap.String("action", "login"),
    zap.String("email", "[email protected]"),        // → "[email protected]" (exposed!)
    zap.Bool("success", true))

🔝 back to top

 

Performance Comparison:

  • 33% faster than Zap's structured logging
  • Zero memory allocations vs Zap's heap allocations
  • Built-in security vs manual implementation required

🔝 back to top

 

License

MIT License - see LICENSE file for details.

 


 

An open source project brought to you by the Cloudresty team.

Website  |  LinkedIn  |  BlueSky  |  GitHub

 

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Info provides emit.Info.FieldWithMessage() and other methods
	Info = InfoLogger{}

	// Error provides emit.Error.FieldWithMessage() and other methods
	Error = ErrorLogger{}

	// Warn provides emit.Warn.FieldWithMessage() and other methods
	Warn = WarnLogger{}

	// Debug provides emit.Debug.FieldWithMessage() and other methods
	Debug = DebugLogger{}
)

Functions

func AddPIIField

func AddPIIField(field string)

AddPIIField adds a custom field pattern to be masked as PII

func AddSensitiveField

func AddSensitiveField(field string)

AddSensitiveField adds a custom field pattern to be masked

func ClearFieldCache

func ClearFieldCache()

ClearFieldCache clears the field pattern cache (for testing or dynamic field updates)

func DebugMsg added in v1.2.0

func DebugMsg(message string)

func DebugStructured added in v1.2.0

func DebugStructured(message string, fields ...ZField)

DebugStructured logs at DEBUG level with structured fields optimization

func ErrorMsg added in v1.2.0

func ErrorMsg(message string)

func ErrorStructured added in v1.2.0

func ErrorStructured(message string, fields ...ZField)

ErrorStructured logs at ERROR level with structured fields optimization

func GetUltraFastTimestamp added in v1.2.0

func GetUltraFastTimestamp() string

GetUltraFastTimestamp returns a cached timestamp string Optimized for sub-20ns performance in the common case

func InfoMsg added in v1.2.0

func InfoMsg(message string)

Simple message logging functions with clear names

func InfoStructured added in v1.2.0

func InfoStructured(message string, fields ...ZField)

InfoStructured logs at INFO level with structured fields optimization

func InfoWithFields

func InfoWithFields(message string, fields map[string]any)

InfoWithFields logs an info message with a map of fields

func JSON

func JSON(severity, message string, optionalParams ...string)

JSON forces JSON output for a single log entry (for special cases)

func Log

func Log(level, message string, optionalParams ...string)

Log is a generic logging function that can be used for custom integrations

func MaskPIIData

func MaskPIIData()

MaskPIIData enables masking of PII fields (default and recommended)

func MaskSensitiveData

func MaskSensitiveData()

MaskSensitiveData enables masking of sensitive fields (default and recommended)

func Plain

func Plain(severity, message string, optionalParams ...string)

Plain forces plain output for a single log entry (for special cases)

func SetAllMasking

func SetAllMasking(enabled bool)

SetAllMasking enables or disables both sensitive and PII masking

func SetComponent

func SetComponent(component string)

SetComponent sets the component name for the default logger

func SetDevelopmentMode

func SetDevelopmentMode()

SetDevelopmentMode disables all masking for development

func SetFormat

func SetFormat(format string)

SetFormat sets the output format (JSON or Plain)

func SetJSONFormat

func SetJSONFormat()

SetJSONFormat switches to JSON output for production

func SetLevel

func SetLevel(level string)

SetLevel sets the log level for the default logger

func SetMaskString

func SetMaskString(mask string)

SetMaskString sets the string used to mask sensitive data

func SetOutput added in v1.2.0

func SetOutput(writer io.Writer)

SetOutput sets the output writer for the default logger

func SetOutputToDiscard added in v1.2.0

func SetOutputToDiscard()

SetOutputToDiscard redirects output to discard for benchmarking

func SetPIIFields

func SetPIIFields(fields []string)

SetPIIFields replaces the default PII field patterns

func SetPIIMaskString

func SetPIIMaskString(mask string)

SetPIIMaskString sets the string used to mask PII data

func SetPIIMode

func SetPIIMode(mode string)

SetPIIMode sets whether to mask PII data

func SetPlainFormat

func SetPlainFormat()

SetPlainFormat switches to plain text output for development

func SetProductionMode

func SetProductionMode()

SetProductionMode enables all masking for production

func SetSensitiveFields

func SetSensitiveFields(fields []string)

SetSensitiveFields replaces the default sensitive field patterns

func SetSensitiveMode

func SetSensitiveMode(mode string)

SetSensitiveMode sets whether to mask sensitive data

func SetShowCaller

func SetShowCaller(show bool)

SetShowCaller enables or disables caller information

func SetTimestampPrecision added in v1.2.0

func SetTimestampPrecision(precision TimestampPrecision)

SetTimestampPrecision sets the global timestamp precision

func SetTimestampPrecisionConfig added in v1.2.0

func SetTimestampPrecisionConfig(precision TimestampPrecision)

SetTimestampPrecisionConfig sets the timestamp precision for the logging system

func SetUltraFastTimestampPrecision added in v1.2.0

func SetUltraFastTimestampPrecision(intervalSeconds int64)

SetUltraFastTimestampPrecision sets the update interval for the ultra-fast cache Lower intervals provide more accurate timestamps but slight performance cost

func SetVersion

func SetVersion(version string)

SetVersion sets the version for the default logger

func ShowPIIData

func ShowPIIData()

ShowPIIData disables masking of PII fields (not recommended for production)

func ShowSensitiveData

func ShowSensitiveData()

ShowSensitiveData disables masking of sensitive fields (not recommended for production)

func WarnMsg added in v1.2.0

func WarnMsg(message string)

func WarnStructured added in v1.2.0

func WarnStructured(message string, fields ...ZField)

WarnStructured logs at WARN level with structured fields optimization

func WithPooledFields

func WithPooledFields(fn func(*PooledFields))

WithPooledFields executes a function with pooled fields and automatically releases them

Types

type BoolZField

type BoolZField struct {
	Key   string
	Value bool
}

BoolZField represents a boolean field with zero allocations

func ZBool

func ZBool(key string, value bool) BoolZField

ZBool creates a zero-allocation bool field

func (BoolZField) IsPII

func (f BoolZField) IsPII() bool

func (BoolZField) IsSensitive

func (f BoolZField) IsSensitive() bool

func (BoolZField) WriteToEncoder

func (f BoolZField) WriteToEncoder(enc *ZeroAllocEncoder)

type DebugLogger added in v1.2.0

type DebugLogger struct{}

DebugLogger provides debug-level logging methods with clear, simple names

func (DebugLogger) Field added in v1.2.0

func (DebugLogger) Field(msg string, fields Fields)

Field logs a debug message with structured fields

func (DebugLogger) KeyValue added in v1.2.0

func (DebugLogger) KeyValue(msg string, keysAndValues ...interface{})

KeyValue logs a debug message with key-value pairs

func (DebugLogger) Msg added in v1.2.0

func (DebugLogger) Msg(message string)

Msg logs a simple debug message

func (DebugLogger) Pool added in v1.2.0

func (DebugLogger) Pool(msg string, fn func(*PooledFields))

Pool logs a debug message using memory-pooled fields

func (DebugLogger) StructuredFields added in v1.2.0

func (DebugLogger) StructuredFields(msg string, fields ...ZField)

StructuredFields logs a debug message with ultra-fast structured fields (Phase 5C)

type DurationZField

type DurationZField struct {
	Key   string
	Value time.Duration
}

DurationZField represents a duration field with zero allocations

func ZDuration

func ZDuration(key string, value time.Duration) DurationZField

ZDuration creates a zero-allocation duration field

func (DurationZField) IsPII

func (f DurationZField) IsPII() bool

func (DurationZField) IsSensitive

func (f DurationZField) IsSensitive() bool

func (DurationZField) WriteToEncoder

func (f DurationZField) WriteToEncoder(enc *ZeroAllocEncoder)

type ErrorLogger added in v1.2.0

type ErrorLogger struct{}

ErrorLogger provides error-level logging methods with clear, simple names

func (ErrorLogger) Field added in v1.2.0

func (ErrorLogger) Field(msg string, fields Fields)

Field logs an error message with structured fields

func (ErrorLogger) KeyValue added in v1.2.0

func (ErrorLogger) KeyValue(msg string, keysAndValues ...interface{})

KeyValue logs an error message with key-value pairs

func (ErrorLogger) Msg added in v1.2.0

func (ErrorLogger) Msg(message string)

Msg logs a simple error message

func (ErrorLogger) Pool added in v1.2.0

func (ErrorLogger) Pool(msg string, fn func(*PooledFields))

Pool logs an error message using memory-pooled fields

func (ErrorLogger) StructuredFields added in v1.2.0

func (ErrorLogger) StructuredFields(msg string, fields ...ZField)

StructuredFields logs an error message with ultra-fast structured fields (Phase 5C)

type Fields

type Fields map[string]any

Fields provides a fluent API for building log fields

func ErrorField

func ErrorField(key string, err error) Fields

ErrorField creates a Fields object with an error field

func Field

func Field(key string, value any) Fields

Field creates a single-field Fields object

func IntField

func IntField(key string, value int) Fields

IntField creates a Fields object with an integer field

func NewFields

func NewFields() Fields

NewFields creates a new Fields instance

func StringField

func StringField(key, value string) Fields

StringField creates a Fields object with a string field

func TimeField added in v1.1.0

func TimeField(key string, value time.Time) Fields

TimeField creates a Fields object with a time field

func (Fields) Add

func (f Fields) Add(key string, value any) Fields

Add is an alias for Set for more natural chaining

func (Fields) Any

func (f Fields) Any(key string, value any) Fields

Any adds a field of any type

func (Fields) Bool

func (f Fields) Bool(key string, value bool) Fields

Bool adds a boolean field

func (Fields) Clone

func (f Fields) Clone() Fields

Clone creates a copy of the Fields

func (Fields) Error

func (f Fields) Error(key string, err error) Fields

Error adds an error field (converts to string)

func (Fields) Float64

func (f Fields) Float64(key string, value float64) Fields

Float64 adds a float64 field

func (Fields) Int

func (f Fields) Int(key string, value int) Fields

Int adds an integer field

func (Fields) Int64

func (f Fields) Int64(key string, value int64) Fields

Int64 adds an int64 field

func (Fields) Merge

func (f Fields) Merge(other Fields) Fields

Merge combines multiple Fields objects

func (Fields) Set

func (f Fields) Set(key string, value any) Fields

Set adds or updates a field

func (Fields) String

func (f Fields) String(key, value string) Fields

String adds a string field

func (Fields) Time added in v1.1.0

func (f Fields) Time(key string, value time.Time) Fields

Time adds a time field (formats as RFC3339)

func (Fields) ToMap

func (f Fields) ToMap() map[string]any

ToMap converts Fields to map[string]any for internal use

func (Fields) With

func (f Fields) With(key string, value any) Fields

With is another alias for Set for more natural chaining

type Float64ZField

type Float64ZField struct {
	Key   string
	Value float64
}

Float64ZField represents a float64 field with zero allocations

func ZFloat64

func ZFloat64(key string, value float64) Float64ZField

ZFloat64 creates a zero-allocation float64 field

func (Float64ZField) IsPII

func (f Float64ZField) IsPII() bool

func (Float64ZField) IsSensitive

func (f Float64ZField) IsSensitive() bool

func (Float64ZField) WriteToEncoder

func (f Float64ZField) WriteToEncoder(enc *ZeroAllocEncoder)

type InfoLogger added in v1.2.0

type InfoLogger struct{}

InfoLogger provides info-level logging methods with clear, simple names

func (InfoLogger) Field added in v1.2.0

func (InfoLogger) Field(msg string, fields Fields)

Field logs an info message with structured fields

func (InfoLogger) KeyValue added in v1.2.0

func (InfoLogger) KeyValue(msg string, keysAndValues ...interface{})

KeyValue logs an info message with key-value pairs

func (InfoLogger) Msg added in v1.2.0

func (InfoLogger) Msg(message string)

Msg logs a simple info message

func (InfoLogger) Pool added in v1.2.0

func (InfoLogger) Pool(msg string, fn func(*PooledFields))

Pool logs an info message using memory-pooled fields

func (InfoLogger) StructuredFields added in v1.2.0

func (InfoLogger) StructuredFields(msg string, fields ...ZField)

StructuredFields logs an info message with structured fields

type Int64ZField

type Int64ZField struct {
	Key   string
	Value int64
}

Int64ZField represents an int64 field with zero allocations

func ZInt64

func ZInt64(key string, value int64) Int64ZField

ZInt64 creates a zero-allocation int64 field

func (Int64ZField) IsPII

func (f Int64ZField) IsPII() bool

func (Int64ZField) IsSensitive

func (f Int64ZField) IsSensitive() bool

func (Int64ZField) WriteToEncoder

func (f Int64ZField) WriteToEncoder(enc *ZeroAllocEncoder)

type IntZField

type IntZField struct {
	Key   string
	Value int
}

IntZField represents an integer field with zero allocations

func ZInt

func ZInt(key string, value int) IntZField

ZInt creates a zero-allocation int field

func (IntZField) IsPII

func (f IntZField) IsPII() bool

func (IntZField) IsSensitive

func (f IntZField) IsSensitive() bool

func (IntZField) WriteToEncoder

func (f IntZField) WriteToEncoder(enc *ZeroAllocEncoder)

type LogEntry

type LogEntry struct {
	Timestamp string         `json:"timestamp"`
	Level     string         `json:"level"`
	Message   string         `json:"message"`
	Component string         `json:"component,omitempty"`
	Version   string         `json:"version,omitempty"`
	File      string         `json:"file,omitempty"`
	Line      int            `json:"line,omitempty"`
	Function  string         `json:"function,omitempty"`
	Fields    map[string]any `json:"fields,omitempty"`
}

LogEntry represents a structured log entry for Kubernetes

type LogLevel

type LogLevel int

LogLevel represents the logging level

const (
	DEBUG LogLevel = iota
	INFO
	WARN
	ERROR
)

func ParseLogLevel

func ParseLogLevel(level string) LogLevel

ParseLogLevel parses a string into a LogLevel

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of the log level

func (LogLevel) StringFast added in v1.2.0

func (l LogLevel) StringFast() string

StringFast returns the string representation of the log level with optimized performance

type Logger

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

Logger represents the JSON logger

func (*Logger) DebugStructured added in v1.2.0

func (l *Logger) DebugStructured(message string, fields ...ZField)

func (*Logger) ErrorStructured added in v1.2.0

func (l *Logger) ErrorStructured(message string, fields ...ZField)

func (*Logger) InfoStructured added in v1.2.0

func (l *Logger) InfoStructured(message string, fields ...ZField)

func (*Logger) WarnStructured added in v1.2.0

func (l *Logger) WarnStructured(message string, fields ...ZField)

type OutputFormat

type OutputFormat int

OutputFormat represents the output format type

const (
	JSON_FORMAT OutputFormat = iota
	PLAIN_FORMAT
)

type PIIDataMode

type PIIDataMode int

PIIDataMode represents how to handle PII data

const (
	MASK_PII PIIDataMode = iota // Default: mask PII data
	SHOW_PII                    // Show PII data (not recommended for production)
)

type PooledFields

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

Optimized Fields implementation with pooling

func NewPooledFields

func NewPooledFields() *PooledFields

NewPooledFields creates a new PooledFields using memory pool

func (*PooledFields) Bool

func (pf *PooledFields) Bool(key string, value bool) *PooledFields

Bool adds a boolean field

func (*PooledFields) Error

func (pf *PooledFields) Error(key string, err error) *PooledFields

Error adds an error field

func (*PooledFields) Float64

func (pf *PooledFields) Float64(key string, value float64) *PooledFields

Float64 adds a float64 field

func (*PooledFields) Int

func (pf *PooledFields) Int(key string, value int) *PooledFields

Int adds an integer field

func (*PooledFields) Int64 added in v1.1.0

func (pf *PooledFields) Int64(key string, value int64) *PooledFields

Int64 adds an int64 field

func (*PooledFields) Release

func (pf *PooledFields) Release()

Release returns the underlying map to the pool

func (*PooledFields) String

func (pf *PooledFields) String(key, value string) *PooledFields

String adds a string field

func (*PooledFields) Time added in v1.1.0

func (pf *PooledFields) Time(key string, value time.Time) *PooledFields

Time adds a time field (formats as RFC3339)

func (*PooledFields) ToMap

func (pf *PooledFields) ToMap() map[string]any

ToMap returns the underlying map

type SensitiveDataMode

type SensitiveDataMode int

SensitiveDataMode represents how to handle sensitive data

const (
	MASK_SENSITIVE SensitiveDataMode = iota // Default: mask sensitive data
	SHOW_SENSITIVE                          // Show sensitive data (not recommended for production)
)

type StringZField

type StringZField struct {
	Key   string
	Value string
}

StringZField represents a string field with zero allocations

func ZString

func ZString(key, value string) StringZField

ZString creates a zero-allocation string field

func (StringZField) IsPII

func (f StringZField) IsPII() bool

func (StringZField) IsSensitive

func (f StringZField) IsSensitive() bool

func (StringZField) WriteToEncoder

func (f StringZField) WriteToEncoder(enc *ZeroAllocEncoder)

type TimeZField

type TimeZField struct {
	Key   string
	Value time.Time
}

TimeZField represents a time field with zero allocations

func ZTime

func ZTime(key string, value time.Time) TimeZField

ZTime creates a zero-allocation time field

func (TimeZField) IsPII

func (f TimeZField) IsPII() bool

func (TimeZField) IsSensitive

func (f TimeZField) IsSensitive() bool

func (TimeZField) WriteToEncoder

func (f TimeZField) WriteToEncoder(enc *ZeroAllocEncoder)

type TimestampPrecision added in v1.2.0

type TimestampPrecision int

TimestampPrecision defines the precision level for timestamps

const (
	NanosecondPrecision TimestampPrecision = iota
	MicrosecondPrecision
	MillisecondPrecision
	SecondPrecision
)

func GetTimestampPrecision added in v1.2.0

func GetTimestampPrecision() TimestampPrecision

GetTimestampPrecision returns the current timestamp precision

func GetTimestampPrecisionConfig added in v1.2.0

func GetTimestampPrecisionConfig() TimestampPrecision

GetTimestampPrecisionConfig returns the current timestamp precision

func ParseTimestampPrecision added in v1.2.0

func ParseTimestampPrecision(precision string) TimestampPrecision

ParseTimestampPrecision parses timestamp precision from string

type WarnLogger added in v1.2.0

type WarnLogger struct{}

WarnLogger provides warn-level logging methods with clear, simple names

func (WarnLogger) Field added in v1.2.0

func (WarnLogger) Field(msg string, fields Fields)

Field logs a warn message with structured fields

func (WarnLogger) KeyValue added in v1.2.0

func (WarnLogger) KeyValue(msg string, keysAndValues ...interface{})

KeyValue logs a warn message with key-value pairs

func (WarnLogger) Msg added in v1.2.0

func (WarnLogger) Msg(message string)

Msg logs a simple warn message

func (WarnLogger) Pool added in v1.2.0

func (WarnLogger) Pool(msg string, fn func(*PooledFields))

Pool logs a warn message using memory-pooled fields

func (WarnLogger) StructuredFields added in v1.2.0

func (WarnLogger) StructuredFields(msg string, fields ...ZField)

StructuredFields logs a warn message with ultra-fast structured fields

type ZField

type ZField interface {
	WriteToEncoder(enc *ZeroAllocEncoder)
	IsSensitive() bool
	IsPII() bool
}

ZField represents a zero-allocation logging field

type ZeroAllocEncoder

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

ZeroAllocEncoder is a high-performance, zero-allocation JSON encoder

Jump to

Keyboard shortcuts

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