nmcslog

package module
v0.0.0-...-11c36d6 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2024 License: MIT Imports: 18 Imported by: 0

README

slog

Golang SLog library for my packages

JSONSchema

package main

import "github.com/invopop/jsonschema"

func main() {
	print(generateSchema())
}

// User is used as a base to provide tests for comments.
type User struct {
	// Unique sequential identifier.
	ID int `json:"id" jsonschema:"required"`
	// Name of the user
	Name string `json:"name"`
}

func generateSchema() string {
	r := new(jsonschema.Reflector)
	if err := r.AddGoComments("github.com/<ACCOUNT>/<REPO>", "./"); err != nil {
		// deal with error
	}
	return r.Reflect(&User{})
}

Documentation

Index

Constants

View Source
const (
	// FormatText specifies the usage of the slog Text output handler.
	FormatText OutputFormat = "TEXT"
	// FormatJSON specifies the usage of the slog JSON output handler.
	FormatJSON OutputFormat = "JSON"

	// LevelTrace defines the Trace Log Level (-8)
	LevelTrace = slog.LevelDebug - 4
	// LevelDebug defines the Debug Log Level (-4)
	LevelDebug = slog.LevelDebug
	// LevelInfo defines the Info Log Level (0)
	LevelInfo = slog.LevelInfo
	// LevelNotice defines the Notice Log Level (2)
	LevelNotice = slog.LevelInfo + 2
	// LevelWarn defines the Warn Log Level (4)
	LevelWarn = slog.LevelWarn
	// LevelError defines the Error Log Level (8)
	LevelError = slog.LevelError
	// LevelFatal defines the Emergency Log Level (12)
	LevelFatal = slog.LevelError + 4

	// DefaultRotateSize is the default max log filesize in Megabytes.
	DefaultRotateSize = 5
	// DefaultRotateKeep is the default number of log files to keep.
	DefaultRotateKeep = 4
	// DefaultRotateAge is the default max age of a log file in days.
	DefaultRotateAge = 7
)
View Source
const (
	ErrorFormat          = "read flag --%s Error: %w"
	Development          = "dev"
	LogConsoleDisable    = "log-console-disable"
	LogConsoleLevel      = "log-console-level"
	LogConsoleFormat     = "log-console-format"
	LogConsoleSource     = "log-console-source"
	LogConsoleFullSource = "log-console-full-source"
	LogFileEnable        = "log-file-enable"
	LogFilePath          = "log-file-path"
	LogFileLevel         = "log-file-level"
	LogFileFormat        = "log-file-format"
	LogFileSource        = "log-file-source"
	LogFileFullSource    = "log-file-full-source"
	LogFileRotateEnable  = "log-file-rotate-enable"
	LogFileRotateStart   = "log-file-rotate-start"
	LogFileRotateSize    = "log-file-rotate-size"
	LogFileRotateKeep    = "log-file-rotate-keep"
	LogFileRotateAge     = "log-file-rotate-age"
)

Variables

View Source
var (
	ErrInvalidLogLevel  = errors.New("invalid log level")
	ErrHandlerDisabled  = errors.New("handler disabled")
	ErrRotatorDisabled  = errors.New("rotator disabled")
	ErrNoHandersEnabled = errors.New("no handlers are enabled")
)
View Source
var CustomLevelNames = map[slog.Leveler]string{
	LevelTrace:  "TRACE",
	LevelNotice: "NOTICE",
	LevelFatal:  "FATAL",
}

CustomLevelNames will replace the SLOG Level output with the given names rather than the lower level + increment.

Functions

func AppendCtx

func AppendCtx(parent context.Context, attr slog.Attr) context.Context

AppendCtx adds a slog attribute to the provided context so that it will be included in any Record created with such context

func AttrFixCustomLogLevelNames

func AttrFixCustomLogLevelNames(groups []string, a slog.Attr) slog.Attr

func AttrRemoveFullSource

func AttrRemoveFullSource(groups []string, a slog.Attr) slog.Attr

func DebugLogger

func DebugLogger() *slog.Logger

DebugLogger will return a default Slog logger at level DEBUG which can be updated via the SetDebugLogger function.

func GenerateSchema

func GenerateSchema(path string) (err error)

func GenerateSchemaWithComments

func GenerateSchemaWithComments(path string) (err error)

func GetConfiguredLogger

func GetConfiguredLogger(logConfig *Config) (logger *slog.Logger, err error)

GetConfiguredLogger will return a logger that is configured according to the given configuration.

func Logger

func Logger() *slog.Logger

Logger will return the default Slog logger which can be updated via the SetDefaultLogger function.

func SetDebugLogger

func SetDebugLogger(l *slog.Logger) *slog.Logger

SetDebugLogger will allow the user to specify a custom logger to be used as the default DEBUG logger.

func SetDefaultLogger

func SetDefaultLogger(l *slog.Logger) *slog.Logger

SetDefaultLogger will allow the user to specify a custom logger to be used as the default logger.

func ValidateSchema

func ValidateSchema(path string) (err error)

func WrapMiddlewareFuncs

func WrapMiddlewareFuncs(handler slog.Handler, mwf ...MiddlewareFunc) slog.Handler

WrapMiddlewareFuncs will wrap multiple Attribute Middlewares around a given Attribute Function.

Types

type AttrStackTrace

type AttrStackTrace struct{}

type AttributeFunc

type AttributeFunc func([]string, slog.Attr) slog.Attr

func WrapAttributeFuncs

func WrapAttributeFuncs(af ...AttributeFunc) AttributeFunc

WrapAttributeFuncs will wrap multiple Attribute Middlewares around a given Attribute Function.

type Config

type Config struct {
	Console  ConsoleOutput
	File     FileOutput
	Handlers []slog.Handler
}

Config is the root configuration for the logging library.

func (*Config) GetHandlers

func (c *Config) GetHandlers() (logger *slog.Logger, err error)

func (*Config) Validate

func (c *Config) Validate() (err error)

Validate will check for common errors in the configuration.

type ConsoleOutput

type ConsoleOutput struct {
	OutputHandler
	// StdOut should only be enabled as a user preference, StdErr is designated for logging and non-interactive output.
	StdOut bool
}

ConsoleOutput defines the settings specific to the console base output.

func (*ConsoleOutput) GetHandler

func (co *ConsoleOutput) GetHandler() (handler slog.Handler, err error)

func (*ConsoleOutput) Validate

func (co *ConsoleOutput) Validate() (err error)

type FileOutput

type FileOutput struct {
	OutputHandler
	// Path is the folder that logs should be written to. If not provided, file based logging will be disabled.
	Path     string `json:",omitempty" jsonschema:"title=Logging Path,example=./logs,default=Current Directory"`
	Filename string
	Rotate   Rotate
	// contains filtered or unexported fields
}

FileOutput defines the settings specific to the file based output.

func (*FileOutput) GetHandler

func (fo *FileOutput) GetHandler() (handler slog.Handler, err error)

func (*FileOutput) GetPath

func (fo *FileOutput) GetPath() string

func (FileOutput) JSONSchemaExtend

func (FileOutput) JSONSchemaExtend(schema *jsonschema.Schema)

JSONSchemaExtend extends the JSON schema for the FileOutput type. It adds conditions and requirements for the "Disable" and "Path" fields.

func (*FileOutput) Validate

func (fo *FileOutput) Validate() (err error)

type LogLevel

type LogLevel struct {
	// Level to cutoff log messages, anything below this level will be dropped.
	Level string
	// contains filtered or unexported fields
}

LogLevel handles the decoding and parsing of a given log level to the slog log level.

func (*LogLevel) DecodeLevel

func (ll *LogLevel) DecodeLevel() (err error)

func (*LogLevel) GetSlogLevel

func (ll *LogLevel) GetSlogLevel() (levelVar slog.Level, err error)

func (*LogLevel) SetSlogLevel

func (ll *LogLevel) SetSlogLevel(newLevel string) (err error)

func (*LogLevel) UnmarshalJSON

func (ll *LogLevel) UnmarshalJSON(data []byte) error

UnmarshalJSON will intercept a JSON string to be converted to OutputFormat.

func (*LogLevel) UnmarshalTOML

func (ll *LogLevel) UnmarshalTOML(data []byte) error

UnmarshalTOML will intercept a TOML string to be converted to OutputFormat.

func (*LogLevel) UnmarshalYAML

func (ll *LogLevel) UnmarshalYAML(data []byte) error

UnmarshalYAML will intercept a YAML string to be converted to OutputFormat.

func (*LogLevel) Validate

func (ll *LogLevel) Validate() (err error)

type MWHandleColors

type MWHandleColors struct {
	ColorMap     map[slog.Level]color.Attribute
	DefaultColor color.Attribute
}

MWHandleColors (WIP) is a middleware that will colorize the LEVEL text.

func (*MWHandleColors) Middleware

func (hc *MWHandleColors) Middleware() slogmulti.Middleware

func (*MWHandleColors) RemoveLevelColor

func (hc *MWHandleColors) RemoveLevelColor(level slog.Level)

func (*MWHandleColors) SetDefaultColors

func (hc *MWHandleColors) SetDefaultColors()

func (*MWHandleColors) SetLevelColor

func (hc *MWHandleColors) SetLevelColor(level slog.Level, format color.Attribute)

type MWHandleContext

type MWHandleContext struct{}

MWHandleContext is a middleware that will extract slog.Attr attributes from the context. https://betterstack.com/community/guides/logging/logging-in-go/#using-the-context-package-with-slog

func (*MWHandleContext) Middleware

func (hc *MWHandleContext) Middleware() slogmulti.Middleware

type MiddlewareFunc

type MiddlewareFunc func(slog.Handler) slog.Handler

type OutputFormat

type OutputFormat string

OutputFormat is the log record output formatting. Currently, JSON and TEXT are supported.

func (*OutputFormat) FromString

func (of *OutputFormat) FromString(format string) error

FromString will convert the given string to the matching OutputFormat.

func (*OutputFormat) Handler

func (of *OutputFormat) Handler(w io.Writer, opts *slog.HandlerOptions) slog.Handler

Handler will return a slog.Handler that matches the configured output format (default=TEXT).

func (*OutputFormat) UnmarshalJSON

func (of *OutputFormat) UnmarshalJSON(data []byte) error

UnmarshalJSON will intercept a JSON string to be converted to OutputFormat.

func (*OutputFormat) UnmarshalTOML

func (of *OutputFormat) UnmarshalTOML(data []byte) error

UnmarshalTOML will intercept a TOML string to be converted to OutputFormat.

func (*OutputFormat) UnmarshalYAML

func (of *OutputFormat) UnmarshalYAML(data []byte) error

UnmarshalYAML will intercept a YAML string to be converted to OutputFormat.

func (*OutputFormat) Validate

func (of *OutputFormat) Validate() (err error)

type OutputHandler

type OutputHandler struct {
	// Disable this logging output.
	Disable bool
	// LogLevel handles the configuration of the current Log Level.
	LogLevel
	// Format of the log output, currently FormatText (default) and FormatJSON are supported.
	Format OutputFormat
	// IncludeSource will include the source code position of the log statement.
	IncludeSource bool
	// IncludeFullSource will include the directory for the source's filename.
	IncludeFullSource bool
	// Middleware is an array of middleware funcs to modify the log record prior to calling the handler.
	// https://github.com/samber/slog-multi#custom-middleware
	Middleware []MiddlewareFunc
	// AttributeFuncs is an array of functions to modify log record attributes.
	AttributeFuncs []AttributeFunc
}

OutputHandler defines the common settings for an output type.

func (*OutputHandler) GetHandler

func (ob *OutputHandler) GetHandler(w io.Writer) (handler slog.Handler, err error)

func (OutputHandler) JSONSchemaExtend

func (OutputHandler) JSONSchemaExtend(schema *jsonschema.Schema)

func (*OutputHandler) Validate

func (ob *OutputHandler) Validate() (err error)

type Rotate

type Rotate struct {
	// Disable log rotation, enabled by default.
	Disable bool `json:",omitempty" jsonschema:"title=Disable Rotation,example=true,default=false"`
	// OnStart will trigger a log rotation on each start of the application.
	OnStart bool `json:",omitempty" jsonschema:"title=Rotate on Start,example=true,default=false"`
	// MaxSize (Megabytes) of a log file to trigger rotation.
	MaxSize int `json:",omitempty" jsonschema:"title=Max Filesize,example=1,default=5"`
	// Keep this many log files.
	Keep int `json:",omitempty" jsonschema:"title=Keep Files,example=3,default=4"`
	// MaxAge (in days) for a log file to triggering rotation.
	MaxAge int `json:",omitempty" jsonschema:"title=Max File Age,example=5,default=7"`
}

func (*Rotate) GetWriter

func (r *Rotate) GetWriter(path string) (w io.Writer, err error)

func (*Rotate) Validate

func (r *Rotate) Validate() (err error)

Jump to

Keyboard shortcuts

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