Documentation
ΒΆ
Overview ΒΆ
Package ion provides an enterprise-grade structured logger tailored for JupiterMeta blockchain services.
It wraps the high-performance Zap logger and OpenTelemetry (OTEL) for observability, offering a simple yet powerful API for consistent logging across microservices.
Key Features ΒΆ
- Zero-allocation hot paths using a custom Zap core.
- Built-in OpenTelemetry (OTEL) integration for log export.
- Automatic context propagation (Trace ID, Span ID).
- Specialized field helpers for blockchain primitives (TxHash, Slot, ShardID).
- Configurable output formats (JSON for production, Pretty for development).
- Log rotation and compression via lumberjack.
Basic Usage ΒΆ
Initialize the logger with a configuration:
import "github.com/JupiterMetaLabs/ion"
func main() {
logger := ion.New(ion.Default())
defer logger.Sync()
logger.Info("application started", ion.F("version", "1.0.0"))
}
Context Support ΒΆ
Use FromContext or WithContext to automatically attach trace identifiers:
func HandleRequest(ctx context.Context) {
// Extracts trace_id and span_id if present in ctx
logger.WithContext(ctx).Info("processing request", ion.F("user_id", 123))
}
Package ion provides enterprise-grade structured logging for JupiterMeta blockchain applications.
Features:
- High-performance Zap core with zero-allocation hot paths
- Multi-destination output (Console, File, OTEL)
- Blockchain-specific field helpers (TxHash, ShardID, Slot, etc.)
- Automatic trace context propagation
- Pretty console output for development
- File rotation via lumberjack
- OpenTelemetry integration for observability
Basic usage:
logger := ion.New(ion.Default())
defer logger.Sync()
logger.Info("server started", ion.F("port", 8080))
With blockchain fields:
import "github.com/JupiterMetaLabs/ion/fields"
logger.Info("transaction routed",
fields.TxHash("abc123"),
fields.ShardID(5),
fields.LatencyMs(12.5),
)
With context (auto-extracts trace_id):
logger.WithContext(ctx).Info("handling request")
Index ΒΆ
- func NewFileWriter(cfg FileConfig) io.Writer
- func RequestIDFromContext(ctx context.Context) string
- func SetGlobal(l Logger)
- func UserIDFromContext(ctx context.Context) string
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithTraceID(ctx context.Context, traceID string) context.Context
- func WithUserID(ctx context.Context, userID string) context.Context
- type Config
- type ConsoleConfig
- type Field
- type FieldType
- type FileConfig
- type Logger
- type OTELConfig
- type TelemetryLog
- func (t *TelemetryLog) Component(name string) *TelemetryLog
- func (t *TelemetryLog) Debug(msg string, fields ...Field)
- func (t *TelemetryLog) Error(msg string, err error, fields ...Field)
- func (t *TelemetryLog) Info(msg string, fields ...Field)
- func (t *TelemetryLog) Instrument(name string) *TelemetryLog
- func (t *TelemetryLog) Level(level zapcore.Level) *TelemetryLog
- func (t *TelemetryLog) Module(name string) *TelemetryLog
- func (t *TelemetryLog) Printf(format string, args ...any)
- func (t *TelemetryLog) Trace(spanName string) *TelemetryLog
- func (t *TelemetryLog) Warn(msg string, fields ...Field)
- func (t *TelemetryLog) WithContext(ctx context.Context) *TelemetryLog
Examples ΒΆ
Constants ΒΆ
This section is empty.
Variables ΒΆ
This section is empty.
Functions ΒΆ
func NewFileWriter ΒΆ
func NewFileWriter(cfg FileConfig) io.Writer
NewFileWriter creates a file writer with rotation using lumberjack. Returns nil if the path is empty.
func RequestIDFromContext ΒΆ
RequestIDFromContext extracts the request ID from context.
func SetGlobal ΒΆ
func SetGlobal(l Logger)
SetGlobal sets the global logger instance. Call this early in application startup.
func UserIDFromContext ΒΆ
UserIDFromContext extracts the user ID from context.
func WithRequestID ΒΆ
WithRequestID adds a request ID to the context. This ID will be automatically included in logs via WithContext().
func WithTraceID ΒΆ
WithTraceID adds a trace ID to the context (for non-OTEL scenarios).
Types ΒΆ
type Config ΒΆ
type Config struct {
// Level sets the minimum log level: debug, info, warn, error.
// Default: "info"
Level string `yaml:"level" json:"level" env:"LOG_LEVEL"`
// Development enables development mode with:
// - Pretty console output by default
// - Caller information in logs
// - Stack traces on error/fatal
Development bool `yaml:"development" json:"development" env:"LOG_DEVELOPMENT"`
// ServiceName identifies this service in logs and OTEL.
// Default: "unknown"
ServiceName string `yaml:"service_name" json:"service_name" env:"SERVICE_NAME"`
// Version is the application version, included in logs.
Version string `yaml:"version" json:"version" env:"SERVICE_VERSION"`
// Console output configuration.
Console ConsoleConfig `yaml:"console" json:"console"`
// File output configuration (with rotation).
File FileConfig `yaml:"file" json:"file"`
// OTEL (OpenTelemetry) exporter configuration.
OTEL OTELConfig `yaml:"otel" json:"otel"`
}
Config holds the complete logger configuration.
func Development ΒΆ
func Development() Config
Development returns a Config optimized for development.
func (Config) WithService ΒΆ
WithService returns a copy of the config with the specified service name.
type ConsoleConfig ΒΆ
type ConsoleConfig struct {
// Enabled controls whether console output is active.
// Default: true
Enabled bool `yaml:"enabled" json:"enabled"`
// Format: "json" for structured JSON, "pretty" for human-readable.
// Default: "json" (production), "pretty" (development)
Format string `yaml:"format" json:"format"`
// Color enables ANSI colors in pretty format.
// Default: true
Color bool `yaml:"color" json:"color"`
// ErrorsToStderr sends warn/error/fatal to stderr, others to stdout.
// Default: true
ErrorsToStderr bool `yaml:"errors_to_stderr" json:"errors_to_stderr"`
}
ConsoleConfig configures console (stdout/stderr) output.
type Field ΒΆ
type Field struct {
Key string
Type FieldType
Integer int64
StringVal string
Float float64
Interface any
}
Field represents a structured logging field (key-value pair). It is designed to be zero-allocation for common types.
type FileConfig ΒΆ
type FileConfig struct {
// Enabled controls whether file output is active.
// Default: false
Enabled bool `yaml:"enabled" json:"enabled"`
// Path is the log file path.
// Example: "/var/log/app/app.log"
Path string `yaml:"path" json:"path"`
// MaxSizeMB is the maximum size in MB before rotation.
// Default: 100
MaxSizeMB int `yaml:"max_size_mb" json:"max_size_mb"`
// MaxAgeDays is the maximum age in days to retain old logs.
// Default: 7
MaxAgeDays int `yaml:"max_age_days" json:"max_age_days"`
// MaxBackups is the maximum number of old log files to keep.
// Default: 5
MaxBackups int `yaml:"max_backups" json:"max_backups"`
// Compress enables gzip compression of rotated log files.
// Default: true
Compress bool `yaml:"compress" json:"compress"`
}
FileConfig configures file output with rotation.
type Logger ΒΆ
type Logger interface {
// Debug logs a message at debug level.
Debug(msg string, fields ...Field)
// Info logs a message at info level.
Info(msg string, fields ...Field)
// Warn logs a message at warn level.
Warn(msg string, fields ...Field)
// Error logs a message at error level with an error.
Error(msg string, err error, fields ...Field)
// Fatal logs a message at fatal level and calls os.Exit(1).
Fatal(msg string, err error, fields ...Field)
// With returns a child logger with additional fields attached.
// Fields are included in all subsequent log entries.
With(fields ...Field) Logger
// WithContext returns a child logger that extracts trace_id, span_id,
// and other context values (request_id, user_id) from the context.
WithContext(ctx context.Context) Logger
// Named returns a named sub-logger.
// The name appears in logs as the "component" field.
Named(name string) Logger
// Sync flushes any buffered log entries.
// Applications should call Sync before exiting.
Sync() error
// Shutdown gracefully shuts down the logger, flushing any buffered logs
// and closing background resources (like OTEL exporters).
Shutdown(ctx context.Context) error
// SetLevel changes the log level at runtime.
// Valid levels: debug, info, warn, error, fatal.
SetLevel(level string)
// GetLevel returns the current log level as a string.
GetLevel() string
}
Logger is the primary logging interface. All methods are safe for concurrent use.
Example ΒΆ
// 1. Initialize the logger
logger := New(Development())
defer logger.Sync()
// 2. Log a simple message
logger.Info("Hello, World!")
// 3. Log with structured fields
logger.Info("User logged in",
F("user_id", 42),
F("ip", "192.168.1.1"),
)
func GetGlobal ΒΆ
func GetGlobal() Logger
GetGlobal returns the global logger instance. Returns a no-op logger if SetGlobal was never called.
func New ΒΆ
New creates a new Logger from the provided configuration. This is the main constructor for ion.
func NewWithOTEL ΒΆ
NewWithOTEL creates a logger with OTEL export enabled. This wires Zap logs to the OpenTelemetry log pipeline.
type OTELConfig ΒΆ
type OTELConfig struct {
// Enabled controls whether OTEL export is active.
// Default: false
Enabled bool `yaml:"enabled" json:"enabled"`
// Protocol: "grpc" or "http". gRPC is recommended for performance.
// Default: "grpc"
Protocol string `yaml:"protocol" json:"protocol"`
// Endpoint is the OTEL collector endpoint.
// Examples: "localhost:4317" (gRPC), "localhost:4318/v1/logs" (HTTP)
Endpoint string `yaml:"endpoint" json:"endpoint"`
// Insecure disables TLS for the connection.
// Default: false
Insecure bool `yaml:"insecure" json:"insecure"`
// Headers are additional headers to send (e.g., auth tokens).
Headers map[string]string `yaml:"headers" json:"headers"`
// Timeout is the export timeout.
// Default: 10s
Timeout time.Duration `yaml:"timeout" json:"timeout"`
// BatchSize is the number of logs per export batch.
// Default: 512
BatchSize int `yaml:"batch_size" json:"batch_size"`
// ExportInterval is how often to export batched logs.
// Default: 5s
ExportInterval time.Duration `yaml:"export_interval" json:"export_interval"`
// Attributes are additional resource attributes for OTEL.
// Example: {"environment": "production", "chain": "solana"}
Attributes map[string]string `yaml:"attributes" json:"attributes"`
}
OTELConfig configures OpenTelemetry log export.
type TelemetryLog ΒΆ
type TelemetryLog struct {
// contains filtered or unexported fields
}
TelemetryLog provides a fluent API for trace-coupled logging. It creates both a log entry AND a trace span in a single call.
Usage:
NewTelemetryLog(logger).
Instrument("example.routing").
Component("pool").
Trace("ROUTE_TX").
Info("transaction routed", fields.TxHash("abc123"))
The log will automatically include trace_id and span_id. Errors automatically mark the span as failed.
func NewTelemetryLog ΒΆ
func NewTelemetryLog(logger Logger) *TelemetryLog
NewTelemetryLog creates a new fluent telemetry logger. Pass the base logger to use for output.
func NewTelemetryLogFromGlobal ΒΆ
func NewTelemetryLogFromGlobal() *TelemetryLog
NewTelemetryLogFromGlobal creates a TelemetryLog using the global logger.
func T ΒΆ
func T() *TelemetryLog
T is a shorthand for creating a TelemetryLog from the global logger.
func (*TelemetryLog) Component ΒΆ
func (t *TelemetryLog) Component(name string) *TelemetryLog
Component sets the component name field.
func (*TelemetryLog) Debug ΒΆ
func (t *TelemetryLog) Debug(msg string, fields ...Field)
Debug logs at debug level with optional trace span.
func (*TelemetryLog) Error ΒΆ
func (t *TelemetryLog) Error(msg string, err error, fields ...Field)
Error logs at error level and marks span as error.
func (*TelemetryLog) Info ΒΆ
func (t *TelemetryLog) Info(msg string, fields ...Field)
Info logs at info level with optional trace span.
func (*TelemetryLog) Instrument ΒΆ
func (t *TelemetryLog) Instrument(name string) *TelemetryLog
Instrument sets the OTEL instrumentation scope name. Example: "my-service.routing", "consensus.engine"
func (*TelemetryLog) Level ΒΆ
func (t *TelemetryLog) Level(level zapcore.Level) *TelemetryLog
Level sets the log level.
func (*TelemetryLog) Module ΒΆ
func (t *TelemetryLog) Module(name string) *TelemetryLog
Module sets the module name field.
func (*TelemetryLog) Printf ΒΆ
func (t *TelemetryLog) Printf(format string, args ...any)
Printf is a convenience method for formatted logging.
func (*TelemetryLog) Trace ΒΆ
func (t *TelemetryLog) Trace(spanName string) *TelemetryLog
Trace sets the span name to create. Example: "ROUTE_TX", "VALIDATE_BLOCK", "CONNECT_NODE"
func (*TelemetryLog) Warn ΒΆ
func (t *TelemetryLog) Warn(msg string, fields ...Field)
Warn logs at warn level with optional trace span.
func (*TelemetryLog) WithContext ΒΆ
func (t *TelemetryLog) WithContext(ctx context.Context) *TelemetryLog
WithContext sets the context for trace propagation. If the context already has a span, the new span will be a child.