gologger

package module
v2.0.5 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2025 License: MIT Imports: 13 Imported by: 0

README

gologger

My small logger library. This is not meant to be used by anyone, I just kept copy pasting this in my projects and thought it is time to have it versioned as dependency.

It has a global extensible logger, featuring 4 extensions:

  • console, basically just standard slog
  • loki, pushing logs in batches to a Loki instance# gologger
  • file, writing logs to a file
  • database, writing logs to a database

Usage

import "github.com/FrauElster/gologger/v2"

// with loki
if err := gologger.Setup("warn"); err != nil {
	return err
}

if lokiURL != "" {
	errLevel, _ := gologger.ParseLevel("error")
	err := gologger.UseLoki(gologger.LokiConfig{
		URL:       lokiURL,
		BatchWait: 5*time.Second,
		Labels: map[string]string{"source":  "myapp","version": "1.0"},
		MinLevel: &errLevel,
	})
	if err != nil {
		return err
	}
}

if logFile != "" {
	err := logger.UseFile(gologger.FileConfig{Path: logFile, LabelsMap: map[string]string{"source": "myApp", "version": "1.0"}})
	if err != nil {
		return err
	}
}

var db *sql.DB // your db connection
if db != nil {
	infoLevel, _ := gologger.ParseLevel("info")
	err := logger.UseSqlite(gologger.DbConfig{DB: db, TableName: "logs",LabelsMap: map[string]string{"source": "myApp", "version": "1.0"}, MinLevel: &infoLevel})
	if err != nil {
		return err
	}
}

gologger.Info("not logged at all")
gologger.Warn("written to stdout, file, and database, but not to loki", "key", "value")
gologger.Error("sent to loki and stdout")

// one can also register stringer functions, which are called for each log entry
gologger.RegisterStringer(func(tm time.Time) string { return tm.Format("2006-01-02") })
gologger.Warn("with timestamp formatting", "time", time.Now())

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

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

Debug logs a debug message with the given arguments

func Error

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

Error logs an error message with the given arguments

func GetLevel

func GetLevel() slog.Level

GetLevel returns the current logging level

func Info

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

Info logs an info message with the given arguments

func OnDebug

func OnDebug(cb LogCallback)

Convenience functions for backward compatibility

func OnError

func OnError(cb LogCallback)

func OnInfo

func OnInfo(cb LogCallback)

func OnWarn

func OnWarn(cb LogCallback)

func ParseLevel added in v2.0.4

func ParseLevel(levelStr string) (slog.Level, error)

ParseLevel converts a string to a slog.Level

func RegisterCallback

func RegisterCallback(level slog.Level, cb LogCallback)

RegisterCallback registers a callback function for the specified level

func RegisterStringer added in v2.0.4

func RegisterStringer[T any](converter func(T) string)

RegisterStringer registers a custom string conversion function for a specific type

func SetLevel

func SetLevel(level slog.Level)

SetLevel sets the logging level

func Setup

func Setup(levelStr string) error

Setup configures the default logger with slog handlers based on the given level string

func StopFile

func StopFile() error

StopFile closes the file writer

func StopLoki

func StopLoki()

StopLoki gracefully shuts down the Loki integration

func UseFile

func UseFile(cfg FileConfig) error

UseFile sets up logging callbacks that write logs to the specified file

func UseLoki

func UseLoki(cfg LokiConfig) error

UseLoki sets up logging callbacks that send logs to a Loki instance

func UseMssqlDb added in v2.0.4

func UseMssqlDb(cfg DbConfig) error

UseMssqlDb sets up logging to a Microsoft SQL Server database

func UseMysqlDb added in v2.0.4

func UseMysqlDb(cfg DbConfig) error

UseMysqlDb sets up logging to a MySQL database

func UsePostgresDb added in v2.0.4

func UsePostgresDb(cfg DbConfig) error

UsePostgresDb sets up logging to a PostgreSQL database

func UseSqlite added in v2.0.4

func UseSqlite(cfg DbConfig) error

UseSqlite sets up logging to a SQLite database

func Warn

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

Warn logs a warning message with the given arguments

Types

type DbConfig added in v2.0.4

type DbConfig struct {
	TableName  string
	DB         *sql.DB
	TimeFormat string
	LabelsMap  map[string]string
	MinLevel   *slog.Level
}

type FileConfig

type FileConfig struct {
	Path       string            // Path to the log file
	TimeFormat string            // Format for timestamps, defaults to time.RFC3339
	FormatJson bool              // Whether to format logs as JSON
	LabelsMap  map[string]string // Labels to be included with every log entry
	MinLevel   *slog.Level       // Minimum log level to write to file
}

type LogCallback

type LogCallback func(msg string, args ...any)

LogCallback is the function signature for log event subscribers

type Logger

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

Logger represents the global logger instance

type LokiConfig

type LokiConfig struct {
	URL       string            // Loki server URL
	BatchWait time.Duration     // Maximum amount of time to wait before sending a batch
	Labels    map[string]string // Default labels to add to all logs
	Tenant    string            // Optional tenant ID for multi-tenancy
	MinLevel  *slog.Level       // Minimum log level to send to Loki
}

type StringConverter added in v2.0.4

type StringConverter func(v any) string

StringConverter is a function that converts a value to its string representation

Jump to

Keyboard shortcuts

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