chronolog

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

README ΒΆ

Chronolog

Chronolog is a lightweight and extensible structured logging library for Go, designed to provide developers with a rich and uniform logging experience across distributed applications.

It supports multiple output formats (JSON and pretty), structured log levels, context propagation for traceability, and common application patterns like operations, events, traces, and errors.


✨ Features

  • βœ… Structured logs with semantic fields
  • 🧡 Context-aware logging (trace/span/parent IDs)
  • πŸ“¦ Extensible log types: Trace, Operation, Message, Lambda, etc.
  • πŸ“ƒ Output formats: JSON (machine-friendly) and Pretty (human-friendly)
  • 🎚️ Minimum log level filtering
  • πŸ”§ Simple configuration

πŸš€ Getting Started

Installation
go get github.com/Astronotify/chronolog
Basic Setup
package main

import (
  "context"
  "github.com/Astronotify/chronolog"
)

func main() {
  chronolog.Setup(chronolog.Config{
    Format: chronolog.FormatPretty,
    MinimumLogLevel:  chronolog.Info,
  })

  ctx := context.Background()
  chronolog.Info(ctx, "Service started successfully")
}

Call chronolog.Setup during your application's initialization phase before invoking any logging functions. If it isn't called, Chronolog will fall back to a basic text logger.


🧱 Log Entry Types

Chronolog provides multiple structured log types:

πŸ”Ή LogEntry

Base log structure, contains:

  • Timestamp
  • Level
  • Message
  • TraceID, SpanID, ParentSpanID
  • Version, CommitHash, BuildTime
  • AdditionalData
πŸ”Ή ErrorLogEntry

Used with chronolog.Error(...):

chronolog.Error(ctx, fmt.Errorf("database unavailable"))
πŸ”Ή OperationRequest / OperationResponse
req := entries.NewOperationRequestLogEntry(ctx, "create-profile", "/profile", "123", "POST")
res := entries.NewOperationResponseLogEntry(req, 200)
πŸ”Ή MessageReceived / Acknowledged / Rejected
recv := entries.NewMessageReceivedLogEntry(ctx, "msg-id", "topic", "consumer-a")
ack := entries.NewMessageAcknowledgedLogEntry(ctx, "msg-id", "topic", "consumer-a")
rej := entries.NewMessageRejectedLogEntry(ctx, "msg-id", "topic", "consumer-a", "invalid payload")
πŸ”Ή TraceBegin / TraceEnd
begin := entries.NewTraceBeginLogEntry(ctx, "cache-warmup")
end := entries.NewTraceEndLogEntryFromBegin(begin)

πŸ“¦ Output Formats

Chronolog supports:

JSON Format (default)
{
  "timestamp": "2025-06-01T14:22:10Z",
  "level": "info",
  "event_type": "LogEntry",
  "message": "Service initialized"
}
Pretty Format (human-readable)
[2025-06-01T14:22:10Z] [INFO] Service initialized trace_id=abc123 span_id=def456 ...

To configure format:

chronolog.Setup(chronolog.Config{
  Format: chronolog.FormatPretty,
})

πŸ›  Configuration

chronolog.Setup(chronolog.Config{
  Writer: os.Stdout,
  Format: chronolog.FormatJSON, // or FormatPretty
  MinimumLogLevel:  chronolog.Info,
})
Minimum Log Level

Logs below the configured level will be discarded.

Level Order Name
1 trace
2 debug
3 info
4 warn
5 error

🌐 Context Enrichment

Use the helpers in the ctx package to add trace information to your logs:

import (
    chronologctx "github.com/Astronotify/chronolog/ctx"
)

ctx := context.Background()
ctx = chronologctx.WithTraceID(ctx, "trace-12345")
chronolog.Info(ctx, "processing request")

πŸ“‚ Project Structure

chronolog/
β”œβ”€β”€ entries/         # Log entry types
β”œβ”€β”€ ctx/             # Public context helpers
β”œβ”€β”€ level/           # Log level definitions
β”œβ”€β”€ internal/        # Utility and handler logic (internal use only)
β”œβ”€β”€ chronolog.go     # Main API
└── README.md

πŸ“š Examples

Several runnable examples live in the examples/ directory:

  • main.go – comprehensive demo covering traces, operations, messages and more.
  • httpserver/ – basic HTTP handler emitting OperationRequestLogEntry and OperationResponseLogEntry for each request.
  • message_consumer/ – illustrates a message lifecycle with Received, Acknowledged and Rejected events.
  • lambda/ – shows how to pair LambdaBeginLogEntry and LambdaEndLogEntry.

Run any example with go run ./examples/<name>.


πŸ“– License

MIT License

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Debug ΒΆ

func Debug(ctx context.Context, message string, additionalData ...map[string]any)

Debug logs a message for detailed debugging information.

This function is intended for developers to log detailed information that is more verbose than info logs, useful for diagnosing issues during development or troubleshooting.

Parameters:

  • ctx (context.Context): The context associated with the log entry, used for metadata like trace IDs.
  • message (string): The log message to be recorded.
  • additionalData (...map[string]any): Variadic slice of maps containing additional key-value data to include in the structured log entry. These maps are merged internally.

Returns:

  • None. This function produces side effects by emitting a log entry through the logger pipeline.

func Entry ΒΆ

func Entry(ctx context.Context, entry any)

Entry logs a fully preconstructed log entry.

This function is useful when you already have a custom or advanced entry object that conforms to your internal logging schema or log serialization format.

Parameters:

  • ctx (context.Context): The execution context.
  • entry (any): A prebuilt structured log entry object. May be a map, struct, or custom type, depending on your logger’s capabilities.

Returns:

  • None. The entry is passed directly to the logger for serialization and dispatch.

func Error ΒΆ

func Error(ctx context.Context, err error, additionalData ...map[string]any)

Error logs a structured error message, along with optional diagnostic data.

This function is intended for actual runtime errors, exceptions, or unexpected failures. It transforms the error into a structured log entry using `entries.NewErrorLogEntry`.

Parameters:

  • ctx (context.Context): The context for propagating metadata like correlation IDs.
  • err (error): The error instance to log. Expected to be non-nil.
  • additionalData (...map[string]any): Optional structured metadata to assist in debugging.

Returns:

  • None. The error is emitted as a structured log entry.

func Info ΒΆ

func Info(ctx context.Context, message string, additionalData ...map[string]any)

Info logs an informational message, optionally enriched with additional contextual data.

This function should be used to log general application events that are useful for understanding normal system behavior (e.g., startup, configuration loaded, user actions).

Parameters:

  • ctx (context.Context): The context associated with the log entry. Used to extract metadata such as trace IDs or user/session information.
  • message (string): The log message to be recorded.
  • additionalData (...map[string]any): Variadic slice of maps containing additional key-value data to include in the structured log entry. These maps are merged internally.

Returns:

  • None. This function produces side effects by emitting a log entry through the logger pipeline.

func Setup ΒΆ

func Setup(cfg Config)

func Trace ΒΆ

func Trace(ctx context.Context, message string, additionalData ...map[string]any)

Trace logs a detailed message for low-level debugging purposes.

This function is intended for developers to trace execution flow and inspect internal state during development or troubleshooting. It should not be used in production unless necessary due to its verbose nature.

Parameters:

  • ctx (context.Context): The context associated with the log entry, used for metadata like trace IDs.
  • message (string): The log message to be recorded.
  • additionalData (...map[string]any): Variadic slice of maps containing additional key-value data to include in the structured log entry. These maps are merged internally.

Returns:

  • None. This function produces side effects by emitting a log entry through the logger pipeline.

func Warn ΒΆ

func Warn(ctx context.Context, message string, additionalData ...map[string]any)

Warn logs a warning message indicating a potential issue that is not necessarily an error.

Use this function to highlight situations that may need investigation but are not critical, such as configuration overrides, slow responses, or unexpected inputs.

Parameters:

  • ctx (context.Context): The execution context for the log entry.
  • message (string): A descriptive warning message.
  • additionalData (...map[string]any): Optional structured data to attach to the log for debugging.

Returns:

  • None. The log entry is processed and forwarded to the underlying logging system.

Types ΒΆ

type Config ΒΆ

type Config struct {
	Writer          io.Writer
	Format          Format
	MinimumLogLevel Level.LogLevel
}

type Format ΒΆ

type Format string
const (
	FormatJSON   Format = "json"
	FormatPretty Format = "pretty"
)

Directories ΒΆ

Path Synopsis
httpserver command
lambda command

Jump to

Keyboard shortcuts

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