rotoslog

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2024 License: MIT Imports: 9 Imported by: 1

README

rotoslog

This package implements a simple log file rotator handler for slog. It works out of the box using the standard JSONHandler (default) and TextHandler for output formatting, but supports custom handlers.

Example using default configuration:

package main

import (
    "log/slog"

    "github/alchemy/rotoslog"
)

func init() {
	h, err := rotoslog.NewHandler(rotoslog.FilePrefix("msg-"))
	if err != nil {
		panic(err)
	}
	logger := slog.New(h)
	slog.SetDefault(logger)
}

Example using custom slog-formatter handler:

package main

import (
	"fmt"
	"io"
	"log/slog"
	"os"
	"testing"

    "github/alchemy/rotoslog"

	formatter "github.com/samber/slog-formatter"
)

func init() {
	formatter1 := formatter.FormatByKey("pwd", func(v slog.Value) slog.Value {
		return slog.StringValue("***********")
	})
	formatter2 := formatter.ErrorFormatter("error")

	builder := func(w io.Writer, opts *slog.HandlerOptions) slog.Handler {
		formattingMiddleware := formatter.NewFormatterHandler(formatter1, formatter2)
		textHandler := NewTextHandler(w, opts)
		return formattingMiddleware(textHandler)
	}
	h, err := rotoslog.NewHandler(rotoslog.HandlerBuilder(builder))
	if err != nil {
		panic(err)
	}
	logger := slog.New(h)
	slog.SetDefault(logger)
}

Documentation

Overview

Package rotoslog provides a slog.Handler implementation that writes to a rotating set of files. Log file names have the following structure: <prefix>(<suffix>|<timestamp>)<extension>. When creating a new handler the user can set various options:

Index

Examples

Constants

View Source
const (
	DEFAULT_FILE_DIR            = "log"
	DEFAULT_FILE_NAME_PREFIX    = ""
	DEFAULT_CURRENT_FILE_SUFFIX = "current"
	DEFAULT_FILE_EXTENSION      = ".log"
	DEFAULT_CURRENT_FILE_NAME   = DEFAULT_FILE_NAME_PREFIX + DEFAULT_CURRENT_FILE_SUFFIX + DEFAULT_FILE_EXTENSION
	DEFAULT_FILE_DATE_FORMAT    = "20060102150405"
	DEFAULT_MAX_FILE_SIZE       = 32 * 1024 * 1024
	DEFAULT_MAX_ROTATED_FILES   = 8
	DEFAULT_MAX_AGE             = time.Duration(maxInt64)
)

Variables

This section is empty.

Functions

func CurrentFileSuffix added in v0.2.0

func CurrentFileSuffix(suffix string) optFun

CurrentFileSuffix sets the current logging file suffix.

func DateTimeLayout added in v0.2.0

func DateTimeLayout(layout string) optFun

DateTimeLayout sets the timestamp layout used in rotated file names.

func FileExt added in v0.2.2

func FileExt(ext string) optFun

FileExt sets the log file extension.

func FilePrefix added in v0.2.0

func FilePrefix(prefix string) optFun

FilePrefix sets the logging file prefix.

func HandlerOptions added in v0.2.0

func HandlerOptions(opts slog.HandlerOptions) optFun

HandlerOptions sets the slog.HandlerOptions for the handler.

func LogDir added in v0.2.0

func LogDir(dir string) optFun

LogDir sets the path to the logging directory

func LogHandlerBuilder added in v0.2.0

func LogHandlerBuilder[H slog.Handler](builder HandlerBuilder[H]) optFun

LogHandlerBuilder sets the HandlerBuilder used for formatting.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"log/slog"
	"math/rand"

	"github.com/alchemy/rotoslog"
	formatter "github.com/samber/slog-formatter"
)

func randomLevel() slog.Level {
	const min = -1
	const max = 2
	return slog.Level(4 * (rand.Intn(max-min+1) + min))
}

func main() {
	const N = 10

	formatter1 := formatter.FormatByKey("pwd", func(v slog.Value) slog.Value {
		return slog.StringValue("***********")
	})
	formatter2 := formatter.ErrorFormatter("error")

	builder := func(w io.Writer, opts *slog.HandlerOptions) slog.Handler {
		formattingMiddleware := formatter.NewFormatterHandler(formatter1, formatter2)
		textHandler := slog.NewTextHandler(w, opts)
		return formattingMiddleware(textHandler)
	}
	h, err := rotoslog.NewHandler(rotoslog.LogHandlerBuilder(builder))
	if err != nil {
		panic(err)
	}
	logger := slog.New(h).With("N", N, "pwd", "123456")
	slog.SetDefault(logger)

	ctx := context.TODO()
	for n := 0; n < N; n++ {
		l := randomLevel()
		if l == slog.LevelError {
			err := fmt.Errorf("random error n° %d", n)
			slog.Log(ctx, l, "tanto va la gatta al lardo che ci lascia lo zampino", "error", err)
			continue
		}
		slog.Log(ctx, l, "tanto va la gatta al lardo che ci lascia lo zampino")
	}
}

func MaxFileSize added in v0.2.0

func MaxFileSize(size uint64) optFun

MaxFileSize sets the size threshold that triggers file rotation. If size is 0 file rotation is disabled.

func MaxRotatedFiles added in v0.2.0

func MaxRotatedFiles(n uint64) optFun

MaxRotatedFiles sets the maximum number of rotated files. When the number of rotated files exceedes this number the oldest rotated file is deleted. Any value of n less than 1 is equivalent to passing 1.

func NewHandler

func NewHandler(options ...optFun) (slog.Handler, error)

NewHandler creates a new handler with the given options.

Example
package main

import ()

func main() {

}

Types

type HandlerBuilder

type HandlerBuilder[H slog.Handler] func(w io.Writer, opts *slog.HandlerOptions) H

HandlerBuilder is a type representing functions used to create handlers to control formatting of logging data.

Jump to

Keyboard shortcuts

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