logger

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: MIT Imports: 12 Imported by: 0

README

NLG Logger

High-performance structured logger for Go built on top of log/slog.

Focused on minimal allocations, high performance, and simple file rotation while staying compatible with the Go standard logging ecosystem.

Use logger to combine colorized console output, JSON logging, file rotation, and daily log archiving through a clean slog-compatible API.

Go Reference Go Report Card Go Version License

Features

  • Standard Compatible: Built directly on top of Go’s standard log/slog package
  • Colorized Terminal Output: Human-readable colored logs for local development
  • Structured JSON Logging: Machine-friendly JSON logs for production environments
  • Automatic Log Directory: Creates the configured log directory automatically
  • File Rotation: Daily and size-based log rotation support
  • Automatic Cleanup: Removes old archived log files automatically
  • Daily Log Naming: Generates files such as 2026-05-11-0001.log
  • Separate Log Levels: Independent minimum levels for terminal and file output
  • Custom Notice Level: Includes LevelNotice support for important console-visible messages
  • Context Logging: Supports InfoContext, WarnContext, ErrorContext, and NoticeContext
  • Structured Chaining: Reusable structured loggers with logger.With(...)
  • Source Tracking: Optional source file and line number logging
  • Thread-Safe Design: Safe for concurrent workloads and server environments
  • Optimized File Writer: High-throughput logging with reduced allocation overhead
  • Graceful Shutdown: Safe logger shutdown through the returned Closer

Requirements

This package requires Go 1.22 or newer.

It is designed for modern Go projects and stays fully compatible with the Go standard logging ecosystem.

  • Go: 1.22 or newer
  • Dependencies: Standard library only

Installation

Add the package to your project using go get:

go get github.com/netlifeguru/logger

Quick Start

The example below initializes the logger as a lightweight extension over Go’s standard log/slog package with colorized terminal output enabled.

During initialization, the logger automatically creates the configured log directory and writes structured JSON log files using daily log rotation.

Example log file:

logs/2026-05-11-0001.log
Example log entry
{
  "time": "2026-05-11T10:47:36.067863+02:00",
  "level": "INFO",
  "msg": "hello world"
}

Default log fields:

  • time - log timestamp
  • level - log severity level
  • msg - log message
package main

import (
	"log/slog"

	"github.com/netlifeguru/logger"
)

func main() {
	closer, err := logger.Init(logger.Config{
		TerminalOutput: true,
	})

	if err != nil {
		panic(err)
	}

	defer closer.Close()

	slog.Info("hello world")
}

Run:

go mod init example.com/myapp
go get github.com/netlifeguru/logger
go run main.go

Configuration

The logger is configured using the Config struct.

  • Dir (string): Directory for log files. Defaults to ./logs.
  • TerminalOutput (bool): Enables or disables console output.
  • MinLevel (slog.Level): Minimum level for file logging. Defaults to slog.LevelInfo.
  • ConsoleMinLevel (slog.Level): Minimum level specifically for console output. If not set, it follows MinLevel.
  • MaxFileSize (int64): Maximum size per log file before rotation. Defaults to 10MB.
  • MaxLogFiles (int): Maximum number of managed log files to keep. Defaults to 5.
  • DisableColors (bool): Disables ANSI colors in console output.
  • AddSource (bool): Adds source file and line information to structured log output.
type Config struct {
	Dir             string
	TerminalOutput  bool
	MinLevel        slog.Level
	ConsoleMinLevel slog.Level
	MaxFileSize     int64
	MaxLogFiles     int
	DisableColors   bool
	AddSource       bool
}

Documentation

Full package documentation, guides, and examples are available at:

https://netlife.guru/docs/go/logger

API reference is also available on pkg.go.dev:

https://pkg.go.dev/github.com/netlifeguru/logger


Performance

Benchmarks performed on Apple M2 Max:

  • ConsoleHandler: ~62 ns/op (1 alloc/op)
  • FileWriter: ~1600 ns/op (0 alloc/op)
  • FileWriter Parallel: ~2000 ns/op (0 alloc/op)

The FileWriter achieves 0 allocations per write thanks to efficient reuse of internal mechanisms.

Benchmark results depend on hardware, Go version, configuration, and output destination.


Why this project exists

This logger focuses on:

  • Predictable performance
  • Minimal heap allocations using sync.Pool for context reuse
  • Simple architecture with no external dependencies
  • Native compatibility with Go's log/slog

Notes

  • Review package-specific concurrency behavior before using it in highly parallel workloads.
  • Check performance characteristics when using this package in latency-sensitive paths.
  • See the package documentation and examples for limitations and recommended usage patterns.

Versioning

This project follows Semantic Versioning.

See CHANGELOG.md for release history and breaking changes.


Contributing

Community contributions, feedback, and improvements are welcome.

Please read CONTRIBUTING.md before submitting pull requests or opening issues.


Code of Conduct

This project follows a Code of Conduct.

Please read CODE_OF_CONDUCT.md before contributing or participating in discussions.


Author

Created and maintained by NetLife Guru s.r.o.


License

MIT License. See LICENSE.

Documentation

Index

Constants

View Source
const LevelNotice slog.Level = -10

Variables

This section is empty.

Functions

func Init

func Init(cfg Config) (io.Closer, error)

func New

func New(cfg Config) (*slog.Logger, io.Closer, error)

func Notice

func Notice(msg string, args ...any)

func NoticeContext

func NoticeContext(ctx context.Context, msg string, args ...any)

func PutContext

func PutContext(ctx *Context)

func With

func With(args ...any) *slog.Logger

Types

type Config

type Config struct {
	Dir             string
	TerminalOutput  bool
	MinLevel        slog.Level
	ConsoleMinLevel slog.Level
	MaxFileSize     int64
	MaxLogFiles     int
	DisableColors   bool
	AddSource       bool
}

type ConsoleHandler

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

func (*ConsoleHandler) Enabled

func (h *ConsoleHandler) Enabled(_ context.Context, l slog.Level) bool

func (*ConsoleHandler) Handle

func (h *ConsoleHandler) Handle(ctx context.Context, r slog.Record) error

func (*ConsoleHandler) WithAttrs

func (h *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*ConsoleHandler) WithGroup

func (h *ConsoleHandler) WithGroup(name string) slog.Handler

type Context

type Context struct {
	Store []KV
}

func GetContext

func GetContext() *Context

func (*Context) AddSlogAttr

func (c *Context) AddSlogAttr(a slog.Attr)

func (*Context) Reset

func (c *Context) Reset()

func (*Context) Set

func (c *Context) Set(key string, value slog.Value)

type FileWriter

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

func NewWriter

func NewWriter(dir string, maxFileSize int64, maxLogFiles int) *FileWriter

func (*FileWriter) Close

func (w *FileWriter) Close() error

func (*FileWriter) Write

func (w *FileWriter) Write(p []byte) (n int, err error)

type KV

type KV struct {
	Key   string
	Value slog.Value
}

Jump to

Keyboard shortcuts

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