sparalog

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2023 License: MIT Imports: 0 Imported by: 0

README

Sparalog

Logging with independent streaming levels.

logger diagram

dispatcher diagram

Features

  • One logger, multiple writers for every logging level.
  • Thread safe.
  • Light and tested.
  • Logs panics from all goroutines without defer.

Usage

import "github.com/modulo-srl/sparalog/logs"

func main() {
    ...
    // Default to stdout/stderror
    logs.Open()
    defer logs.Done()
    ...
    logs.Error("error!")
    logs.Infof("%s", "info!")
    ...
}
Multiple writers
    // New writer to file.
    wf := logs.NewFileWriter("errors.log")

    // Reset the default writer to file for all levels.
    logs.ResetWriters(wf)

    logs.AddLevelsWriter(
        []sparalog.Level{
            sparalog.FatalLevel, sparalog.ErrorLevel, sparalog.WarnLevel,
        },
        ws,
    )
    
    // New Telegram writer.
    wt := logs.NewTelegramWriter("api key", channel id)
    
    // Logs fatals to Telegram too.
    logs.AddLevelWriter(sparalog.FatalLevel, wt)

    logs.Open()
    defer logs.Done()

    ...
Panics watcher
    // Logs fatals to Telegram too.
    wt := logs.NewTelegramWriter("api key", channel id)
    logs.AddLevelWriter(sparalog.FatalLevel, wt, "")

    // Start the watcher.
    // Please note:
    // - Writers, or at least the fatal level writers, must to be set before this calls.
    // - Avoid this call in debugging session!
    logs.StartPanicWatcher()

    logs.Open()

    // Test
    go func() {
        i := 0
        i := 1 / i  // the panic here will be logged
    }()
Misc
    // Enable stack tracke for warning level.
    EnableStacktrace(sparalog.WarnLevel, true)

    ...

    // Mute info, debug and trace levels.
    logs.Mute(sparalog.InfoLevel, true)
    logs.Mute(sparalog.DebugLevel, true)
    logs.Mute(sparalog.TraceLevel, true)

Child loggers
    type module struct {
        log sparalog.Logger
        ...
    }

    func (m *module) init() {
        // This logger will forward to the Default logger writers.
        m.log = logs.NewChildLogger("my module")

        ...

        // Will be logged by Default logger, using "my module" prefix.
        m.log.Error("error!")
    }    

Notes

  • Writers internal errors are redirected to the default writer.

Copyright 2020,2023 Modulo srl - Licensed under the MIT license

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CriticalLevels = []Level{FatalLevel, ErrorLevel, WarnLevel}

CriticalLevels lists critical levels.

View Source
var DebugLevels = []Level{DebugLevel, TraceLevel}

DebugLevels lists debugging purpose levels.

View Source
var FatalExitCode = 1

FatalExitCode is the Exit Code used in Fatal() and Fatalf().

Levels is a constant of all logging levels.

View Source
var LevelsIcons = [LevelsCount]string{
	"\xE2\x9D\x8C", "\xE2\x9D\x97", "\xE2\x9A\xA0", "\xE2\x84\xB9", "\xF0\x9F\x90\x9B", "\xF0\x9F\x94\x8E",
}

LevelsIcons is a constant of all logging levels UTF8 icons.

View Source
var LevelsString = [LevelsCount]string{
	"fatal", "error", "warning", "info", "debug", "trace",
}

LevelsString is a constant of all logging levels names.

Functions

This section is empty.

Types

type Context

type Context interface {
	SetTag(string, string)
	SetData(string, interface{})
	SetPrefix(format string, tags []string)

	AssignContext(Context, bool)

	Tags() map[string]string
	Data() map[string]interface{}

	Prefix() (string, []string)

	RenderPrefix() string
}

Context defines the interface for contextualized logging data.

type Dispatcher

type Dispatcher interface {
	// Mute mute/unmute a specific level.
	Mute(Level, bool)

	// EnableStacktrace enable stacktrace for a specific level.
	EnableStacktrace(Level, bool)

	// ResetWriters reset the writers for all the levels to an optional default writer.
	ResetWriters(Writer)
	// ResetLevelWriters remove all level's writers and reset to an optional default writer.
	ResetLevelWriters(Level, Writer)
	// ResetLevelsWriters remove specific levels writers and reset to an optional default writer.
	ResetLevelsWriters([]Level, Writer)
	// AddWriter add a writer to all levels.
	AddWriter(Writer)
	// AddLevelWriter add a writer to a level.
	AddLevelWriter(Level, Writer)
	// AddLevelsWriter add a writer to several levels.
	AddLevelsWriter([]Level, Writer)
	// RemoveWriter delete a specific writer from level.
	RemoveWriter(Level, WriterID)

	// LevelState return a level status.
	LevelState(Level) LevelState

	// Dispatch sends an Item to the level writers.
	Dispatch(Item)

	// Start starts all the writers.
	Start() error
	// Stop terminate all the writers.
	Stop()
}

Dispatcher is the base class of the logger dispatcher.

type Item

type Item interface {
	Context

	Level() Level

	Line() string
	SetLine(string)

	StackTrace() string
	GenerateStackTrace(callsToSkip int)
	SetStackTrace(string)

	ToString(timestamp, level bool) string

	Log()

	SetLogger(ItemLogger)
}

Item is the single item of log.

type ItemLogger

type ItemLogger interface {
	LogItem(Item)
}

ItemLogger used by Item.SetLogger(), Item.Log().

type Level

type Level int

Level type.

const (
	// FatalLevel - Shutdown of the service or application to prevent data loss (or further data loss).
	// Wake up the SysAdmin!
	// Stack trace enabled by default.
	FatalLevel Level = iota
	// ErrorLevel - Any error which is fatal to the operation, but not the service or application
	// (can't open a required file, missing data, incorrect connection strings, missing services, etc.).
	// SysAdmin should be notified automatically, but doesn't need to be dragged out of bed.
	// Stack trace enabled by default.
	ErrorLevel
	// WarnLevel - Anything that can potentially cause application oddities, but automatically recovered.
	WarnLevel
	// InfoLevel - General operational entries about what's going on inside the service or application.
	// Should be the out-of-the-box level.
	InfoLevel
	// DebugLevel - Usually enabled only when debugging. Very verbose logging.
	// Muted by default.
	DebugLevel
	// TraceLevel - For tracing the code and trying to find one part of a function specifically.
	// Muted by default.
	TraceLevel

	LevelsCount
)

Logging levels.

type LevelState

type LevelState struct {
	Muted      bool
	Stacktrace bool
	NoWriters  bool
}

LevelState is the status of specific logging level, returned by Dispatcher.LevelState().

type Logger

type Logger interface {
	// Fatal sends to Default logger fatal stream using the same fmt.Print() interface.
	Fatal(args ...interface{})
	// Fatalf sends to Default logger fatal stream using the same fmt.Printf() interface.
	Fatalf(format string, args ...interface{})

	// Error sends to Default logger error stream using the same fmt.Print() interface.
	Error(args ...interface{})
	// Errorf sends to Default logger error stream using the same fmt.Printf() interface.
	Errorf(format string, args ...interface{})

	// Warn sends to Default logger warning stream using the same fmt.Print() interface.
	Warn(args ...interface{})
	// Warnf sends to Default logger warning stream using the same fmt.Printf() interface.
	Warnf(format string, args ...interface{})

	// Info sends to Default logger info stream using the same fmt.Print() interface.
	Info(args ...interface{})
	// Infof sends to Default logger info stream using the same fmt.Printf() interface.
	Infof(format string, args ...interface{})

	// Debug sends to Default logger debug stream using the same fmt.Print() interface.
	Debug(args ...interface{})
	// Debugf sends to Default logger debug stream using the same fmt.Printf() interface.
	Debugf(format string, args ...interface{})

	// Trace sends to Default logger trace stream using the same fmt.Print() interface.
	Trace(args ...interface{})
	// Tracef sends to Default logger trace stream using the same fmt.Printf() interface.
	Tracef(format string, args ...interface{})

	// Print sends to Default logger info stream using the same fmt.Print() interface.
	Print(args ...interface{}) // Info() alias
	// Printf sends to Default logger info stream using the same fmt.Printf() interface.
	Printf(format string, args ...interface{}) // Infof() alias

	// SetContextTag sets a context tag.
	SetContextTag(string, string)
	// SetContextData sets a context data payload.
	SetContextData(string, interface{})
	// SetContextPrefix sets the context prefix.
	// Tags is the list of the tags names that will be rendered according to format.
	SetContextPrefix(format string, tags []string)

	// NewItem generate a new log item for the default logger.
	NewItem(Level, ...string) Item
	// NewItemf generate a new log item for the default logger.
	NewItemf(Level, string, ...string) Item
	// NewError generate a new log item wrapping an error.
	NewError(error) Item
	// NewErrorf generate a new log item wrapping an error, as Errorf().
	NewErrorf(string, ...interface{}) Item

	// Log to level stream - entry point for all the helpers; thread safe.
	Log(Level, string, ...interface{})
	// Logf logs to level stream using format - entry point for all the helpers; thread safe.
	Logf(Level, string, string, ...interface{})

	// CloneContext returns a clone of the current context.
	CloneContext() Context

	// Open start the loggers and all the writers.
	Open() error
	// Close terminates loggers and all the writers.
	Close()
}

Logger is the base interface of the logger.

type Writer

type Writer interface {
	// Get writer ID
	ID() WriterID

	// SetFeedbackChan set a channel to the level default writer of the logger.
	SetFeedbackChan(chan Item)

	// Feedback generate an item and send it to the level default writer of the logger.
	Feedback(Level, ...interface{})
	// Feedbackf generate an item and send it to the level default writer of the logger.
	Feedbackf(Level, string, ...interface{})
	// FeedbackItem send an item to the level default writer of ther logger.
	FeedbackItem(Item)

	// Write writes an item.
	Write(Item)

	// Open starts the writer.
	Open() error
	// Close terminates the writer.
	Close()
}

Writer is the writer used by the Logger for one or more log levels.

type WriterID

type WriterID string

WriterID is the Writer identifier in the level writers list.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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