typelog

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 12 Imported by: 19

README

Typelog - Static typed structured logging

Description

This project araised from the need to log backend applications, aws lambdas and other stuff in modern cloud ecosystem. Logging systems today are able easily parsing JSON format out of the box. Static typing approach brings here consistent way to define key values to final msg, as well as easier following Domain Driven Design, where logs consistently describe what they log. Static typed logging brings easy refactoring to any present logs.

Features

  • Accepts static typed components as optional params
    • it will not accept any options as slog.
    • has shortcut WithFields, to make clone of the logger with default logging fields
  • Easy to turn on/off parameters by environment variables
    • Ability to define different log levels for different created loggers
  • Easier turning complex objects into structured logging
    • accepts maps and structs as its params. It will parse them on their own.
  • has ability to show "scope" of current logging (from which module the logs are)
  • has ability to grab otlp span id/trace id if they are present

See folder examples

Alternative Versions

How to use

install with go get github.com/darklab8/go-utils

examples/logger/main.go

package logger

import "github.com/darklab8/go-utils/typelog"

var Log *typelog.Logger = typelog.NewLogger("typelog")

examples/params_test.go

package examples

import (
	"log/slog"
	"testing"
	"time"

	"github.com/darklab8/go-utils/examples/logger"
	"github.com/darklab8/go-utils/typelog"
)

func TestUsingInitialized(t *testing.T) {

	logger.Log.Debug("123")

	logger.Log.Debug("123", typelog.TestParam(456))

	logger1 := logger.Log.WithFields(typelog.Int("worker_id", 10))

	logger1.Info("Worker made action1")
	logger1.Info("Worker made action2")

	logger2 := logger.Log.WithFields(typelog.Float64("smth", 13.54))
	logger2.Debug("try now")
	logger1.Info("Worker made action1", typelog.Bool("is_check", false))
}

func TestSlogging(t *testing.T) {

	logger := typelog.NewLogger("test", typelog.WithLogLevel(typelog.LEVEL_DEBUG))
	logger.Debug("123")

	logger.Debug("123", typelog.TestParam(456))
}

func NestedParam(value string) typelog.LogType {
	return func(c *typelog.LogAtrs) {
		c.Append(typelog.Group("nested", typelog.TurnMapToAttrs(map[string]any{
			"smth":   "abc",
			"number": 123,
		})...))
	}
}

type Smth struct {
	Value1  string
	Number1 int
}

func NestedStructParam(value string) typelog.LogType {
	return func(c *typelog.LogAtrs) {
		c.Append(
			typelog.Group("nested", typelog.TurnStructToAttrs(Smth{Value1: "123", Number1: 4})...),
			slog.Int("not_nested", 345),
		)
	}
}

func TestNested(t *testing.T) {
	logger := typelog.NewLogger("test", typelog.WithLogLevel(typelog.LEVEL_DEBUG), typelog.WithJsonFormat(true))

	logger.Debug("123", NestedParam("abc"))
	logger.Debug("456", NestedStructParam("abc"))
}

func TestCopyingLoggers(t *testing.T) {
	logger := typelog.NewLogger("test", typelog.WithLogLevel(typelog.LEVEL_DEBUG), typelog.WithJsonFormat(true))

	logger1 := logger.WithFields(typelog.String("smth", "123"))
	logger2 := logger1.WithFields(typelog.Int("smth2", 2), typelog.String("anotheparam", "abc"))
	logger3 := logger2.WithFields(typelog.Time("smth3", time.Now()))

	logger1.Info("logger1 printed")
	logger2.Info("logger2 printed")
	logger3.Info("logger3 printed")
}

Documentation

Overview

Package typelog is a slog modified for extra static type safety and extra boilerplating out of the box

Index

Constants

View Source
const (
	TOOL_NAME = "typelog"
)

Variables

View Source
var RegisteredLoggers []*Logger

RegisteredLoggers leaves option for end applications to access all registered loggers and choosing their own log levels to override for them

Functions

func CompL

func CompL[T any, V any](objs []T, lambda func(x T) V) []V

func GetCallingFile

func GetCallingFile(level int) string

func Group

func Group(name string, attrs ...slog.Attr) slog.Attr

func IsMsgEnabled

func IsMsgEnabled(current_level, msg_level LogLevel) bool

func LevelToInt

func LevelToInt(level LogLevel) int

func StructToMap

func StructToMap(somestruct any) map[string]any

func TurnMapToAttrs

func TurnMapToAttrs(params map[string]any) []slog.Attr

func TurnStructToAttrs

func TurnStructToAttrs(somestruct any) []slog.Attr

Types

type LogAtrs

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

func (*LogAtrs) Append

func (s *LogAtrs) Append(params ...slog.Attr)

func (LogAtrs) Render

func (s LogAtrs) Render() []SlogAttr

type LogLevel

type LogLevel string
const (
	LEVEL_DEBUG        LogLevel = "DEBUG"
	LEVEL_INFO         LogLevel = "INFO"
	LEVEL_WARN         LogLevel = "WARN"
	LEVEL_ERROR        LogLevel = "ERROR"
	LEVEL_FATAL        LogLevel = "FATAL"
	LEVEL_DEFAULT_WARN LogLevel = ""
)

func (LogLevel) ToStr

func (l LogLevel) ToStr() string

type LogType

type LogType func(r *LogAtrs)

func Actual

func Actual(value any) LogType

func Any

func Any(key string, value any) LogType

func Args

func Args(value []string) LogType

func Bool

func Bool(key string, value bool) LogType

func Bytes

func Bytes(key string, value []byte) LogType

func CtxOpts

func CtxOpts(ctx context.Context, opts ...LogType) []LogType

func Expected

func Expected(value any) LogType

func Float32

func Float32(key string, value float32) LogType

func Float64

func Float64(key string, value float64) LogType

func Int

func Int(key string, value int) LogType

func Int64

func Int64(key string, value int64) LogType

func Items

func Items[T any](item_name string, value []T) LogType

func Map

func Map(value map[string]any) LogType

func NestedMap

func NestedMap(key string, value map[string]any) LogType

func NestedStruct

func NestedStruct(key string, value StructType) LogType

func OptError

func OptError(err error) LogType

func Records

func Records[T any](value []T) LogType

func String

func String(key string, value string) LogType

func Struct

func Struct(value StructType) LogType

func TestParam

func TestParam(value int) LogType

func Time

func Time(key string, value time.Time) LogType

type Logger

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

func NewLogger

func NewLogger(
	name string,
	options ...LoggerParam,
) *Logger

func (*Logger) CheckDebug

func (l *Logger) CheckDebug(err error, msg string, opts ...LogType) bool

func (*Logger) CheckDebugCtx

func (l *Logger) CheckDebugCtx(ctx context.Context, err error, msg string, opts ...LogType)

func (*Logger) CheckError

func (l *Logger) CheckError(err error, msg string, opts ...LogType) bool

func (*Logger) CheckErrorCtx

func (l *Logger) CheckErrorCtx(ctx context.Context, err error, msg string, opts ...LogType)

func (*Logger) CheckFatal

func (l *Logger) CheckFatal(err error, msg string, opts ...LogType)

CheckFatal has shorter error output in comparison to CheckPanic

func (*Logger) CheckFatalCtx

func (l *Logger) CheckFatalCtx(ctx context.Context, err error, msg string, opts ...LogType)

func (*Logger) CheckPanic

func (l *Logger) CheckPanic(err error, msg string, opts ...LogType)

func (*Logger) CheckPanicCtx

func (l *Logger) CheckPanicCtx(ctx context.Context, err error, msg string, opts ...LogType)

func (*Logger) CheckWarn

func (l *Logger) CheckWarn(err error, msg string, opts ...LogType) bool

func (*Logger) CheckWarnCtx

func (l *Logger) CheckWarnCtx(ctx context.Context, err error, msg string, opts ...LogType)

func (*Logger) Debug

func (l *Logger) Debug(msg string, opts ...LogType)

func (*Logger) DebugCtx

func (l *Logger) DebugCtx(ctx context.Context, msg string, opts ...LogType)

func (*Logger) Error

func (l *Logger) Error(msg string, opts ...LogType)

Error is bad but program can recover from it

func (*Logger) ErrorCtx

func (l *Logger) ErrorCtx(ctx context.Context, msg string, opts ...LogType)

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, opts ...LogType)

Fatal when encountered, Program is not allowed to run further with fatal

func (*Logger) FatalCtx

func (l *Logger) FatalCtx(ctx context.Context, msg string, opts ...LogType)

func (*Logger) GetName

func (l *Logger) GetName() string

func (*Logger) Info

func (l *Logger) Info(msg string, opts ...LogType)

func (*Logger) InfoCtx

func (l *Logger) InfoCtx(ctx context.Context, msg string, opts ...LogType)

func (*Logger) Initialized

func (l *Logger) Initialized() *Logger

func (*Logger) OverrideOption

func (l *Logger) OverrideOption(options ...LoggerParam) *Logger

OverrideOption for overrides by external libraries

func (*Logger) Panic

func (l *Logger) Panic(msg string, opts ...LogType)

func (*Logger) PanicCtx

func (l *Logger) PanicCtx(ctx context.Context, msg string, opts ...LogType)

func (*Logger) Warn

func (l *Logger) Warn(msg string, opts ...LogType)

Warn is for just potentially bad behavior to be aware of

func (*Logger) WarnCtx

func (l *Logger) WarnCtx(ctx context.Context, msg string, opts ...LogType)

func (*Logger) WithFields

func (l *Logger) WithFields(opts ...LogType) *Logger

func (*Logger) WithScope

func (l *Logger) WithScope(scope string) *Logger

type LoggerParam

type LoggerParam func(r *Logger)

func WithFileShowing

func WithFileShowing(state bool) LoggerParam

file showing works meh. Use scopes instead

func WithIoWriter

func WithIoWriter(writer io.Writer) LoggerParam

func WithJsonFormat

func WithJsonFormat(state bool) LoggerParam

func WithLogLevel

func WithLogLevel(log_level_str LogLevel) LoggerParam

func WithLogLevelStr

func WithLogLevelStr(log_level_str string) LoggerParam

func WithScope

func WithScope(value bool) LoggerParam

type SlogAttr

type SlogAttr = any

type StructType

type StructType = any

type TypelogEnvs

type TypelogEnvs struct {
	EnableJson        bool
	EnableFileShown   bool
	EnableScopesShown bool
}
var Env TypelogEnvs = TypelogEnvs{
	EnableJson:        os.Getenv(strings.ToUpper(TOOL_NAME)+"_LOG_JSON") == "true" || os.Getenv(strings.ToUpper(TOOL_NAME)+"_JSON") == "true",
	EnableFileShown:   os.Getenv(strings.ToUpper(TOOL_NAME)+"_LOG_FILE_SHOWING") == "true" || os.Getenv(strings.ToUpper(TOOL_NAME)+"_FILES") == "true",
	EnableScopesShown: os.Getenv(strings.ToUpper(TOOL_NAME)+"_SCOPES") == "true",
}

Jump to

Keyboard shortcuts

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