loggie

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: May 8, 2025 License: MIT Imports: 5 Imported by: 0

README

loggie 🧠⚡️ — Context-Aware Logger for Go

Context-aware, pluggable logger for Go web applications.
No more passing logger through every function — just use context.Context.


🚀 What is loggie?

loggie helps you embed a structured logger inside context.Context, so you can log from any layer — service, repository, or handler — with a consistent trace_id, user_id, or any custom field.

It supports Zap, Logrus, OpenTelemetry, and works with any web framework.


✨ Features

✅ Structured logging via context.Context
✅ Auto-generated trace_id per request
✅ OTEL-compatible (extracts trace_id from spans)
✅ Custom fields via loggie.WithCustomField()
✅ Framework-agnostic logger injection
✅ Zap / Logrus support
✅ No-op fallback logger
✅ Fx lifecycle and context cancellation compatible


📦 Installation

go get github.com/ditthkr/loggie

🧠 Injecting Logger in Middleware

Use loggie.Injection(ctx, logger) inside any middleware, from any web framework.

ctx, traceId := loggie.Injection(req.Context(), logger)
✅ Fiber
app.Use(func(c *fiber.Ctx) error {
	ctx, traceId := loggie.Injection(c.UserContext(), logger)
	c.SetUserContext(ctx)
	c.Set("X-Trace-Id", traceId)
	return c.Next()
})
✅ Gin
r.Use(func(c *gin.Context) {
	ctx, traceId := loggie.Injection(c.Request.Context(), logger)
	c.Request = c.Request.WithContext(ctx)
	c.Writer.Header().Set("X-Trace-Id", traceId)
	c.Next()
})
✅ Echo
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx, traceId := loggie.Injection(c.Request().Context(), logger)
		req := c.Request().WithContext(ctx)
		c.SetRequest(req)
		c.Response().Header().Set("X-Trace-Id", traceId)
		return next(c)
	}
})

🔌 Logger Interface

type Logger interface {
    Info(msg string, fields ...any)
    Error(msg string, fields ...any)
    With(fields ...any) Logger
}
✅ Supported Adapters
Logger Package
Zap loggie.ZapLogger
Logrus loggie/logruslogger

📄 Usage Example

log := loggie.FromContext(ctx)
log.Info("Order created", "user_id", 123)

📤 Output (Zap or Logrus):

{
  "msg": "Order created",
  "trace_id": "...",
  "user_id": 123
}

🧰 Utilities

Function Description
Injection(ctx, logger) Inject logger + trace_id into ctx
FromContext(ctx) Get logger with fields from ctx
WithTraceId(ctx) Add trace_id manually
TraceId(ctx) Get trace_id (auto or OTEL)
WithLogger(ctx, logger) Attach logger
WithCustomField(ctx, key, val) Add any key-value field
DefaultLogger() Get fallback no-op logger

🌐 OpenTelemetry Support

If a context already contains an OTEL span, loggie will extract its trace_id:

span := trace.SpanFromContext(ctx)
traceId := span.SpanContext().TraceId().String()

You don’t need to do anything extra — TraceId(ctx) handles it automatically.


📃 License

MIT © 2025 @ditthkr

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Injection added in v0.2.5

func Injection(ctx context.Context, logger Logger) (context.Context, string)

Injection injects logger and trace_id into a context. Use it inside any web framework middleware.

func TraceId

func TraceId(ctx context.Context) string

TraceId returns the current trace Id from the context.

It checks the following, in order:

  1. If an OpenTelemetry span exists in the context and has a valid TraceId, it is returned.
  2. If a local trace Id was previously stored in context via WithTraceId(), it is returned.
  3. Otherwise, a new UUId is generated and returned.

func WithCustomField

func WithCustomField(ctx context.Context, key string, value any) context.Context

WithCustomField adds a custom key-value pair to the context. These fields will be automatically injected into log output.

func WithLogger

func WithLogger(ctx context.Context, logger Logger) context.Context

WithLogger stores the given logger inside the context. It can be retrieved later using FromContext.

func WithTraceId

func WithTraceId(ctx context.Context) (context.Context, string)

WithTraceId returns a new context with a generated or existing trace Id, and the trace Id itself as a string.

It first checks if a trace Id exists in the context, otherwise it generates a new UUId. This function is compatible with both OpenTelemetry-based contexts and local fallback mode.

Types

type Logger

type Logger interface {
	Info(msg string, fields ...any)
	Error(msg string, fields ...any)
	With(fields ...any) Logger
}

Logger is the main interface used for logging. It mimics a simplified version of structured loggers like Zap or Logrus.

func DefaultLogger added in v0.2.1

func DefaultLogger() Logger

DefaultLogger returns the internal fallback logger used when no logger is found. This logger does nothing and is safe to call anywhere.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext retrieves the logger from context. If no logger is found, it returns a default no-op logger.

type LogrusLogger added in v0.2.3

type LogrusLogger struct {
	L *logrus.Entry
}

func (*LogrusLogger) Error added in v0.2.3

func (l *LogrusLogger) Error(msg string, fields ...any)

func (*LogrusLogger) Info added in v0.2.3

func (l *LogrusLogger) Info(msg string, fields ...any)

func (*LogrusLogger) With added in v0.2.3

func (l *LogrusLogger) With(fields ...any) Logger

type ZapLogger

type ZapLogger struct {
	L *zap.Logger
}

func (*ZapLogger) Error

func (r *ZapLogger) Error(msg string, fields ...any)

func (*ZapLogger) Info

func (r *ZapLogger) Info(msg string, fields ...any)

func (*ZapLogger) With

func (r *ZapLogger) With(fields ...any) Logger

Directories

Path Synopsis
examples
echo command
fiber command
gin command

Jump to

Keyboard shortcuts

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