slogflags

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2025 License: MIT Imports: 5 Imported by: 4

README

slogflags

PkgGoDev

Provides flags to configure the go structured logging package.

Why?

How logs are formatted and what levels should be output depend on where and how an application is deployed. For general purpose applications, they can't really be set at compile time: some users will want JSON logs, others may want to enable debug log levels to diagnose an issue, and so on.

The slog package doesn't provide a nice way of handling this, so slogflags was created.

How?

In the most basic case, import this package, call flag.Parse(), and then retrieve your brand new logger by calling slogflags.Logger():

package main

import (
	"flag"
	"github.com/csmith/slogflags"
)

func main() {
	flag.Parse()
	l := slogflags.Logger()
	l.Warn("Danger", "user", "Will Robinson")
}

You can then run the app and specify --log.level (one of "debug", "info", "warn" and "error") and --log.format (either "text" or "json").

More advanced usage

You can pass options in to the Logger call to change the default behaviour. See the godocs for a full list. The most useful one is perhaps SetDefault, which sets the new logger as the default for the slog package. This also enables bridging of calls from the log package.

package main

import (
	"flag"
	"github.com/csmith/slogflags"
	"log"
)

func main() {
	flag.Parse()
	l := slogflags.Logger(slogflags.WithSetDefault(true))
	l.Warn("Danger", "user", "Will Robinson")
	log.Printf("I'll show up properly now too!")
}

Licence/credits/contributions etc

Released under the MIT licence. See LICENCE for full details.

Contributions are welcome! Please feel free to open issues or send pull requests.

Documentation

Overview

Package slogflags provides flags to configure log/slog.

Basic usage

Simply call flag.Parse and then call Logger to obtain a configured slog instance. Two new flags will be available to users of your app: `--log.level` which accepts a textual level ("debug", "info", "warn" or "error") and `--log.format` which accepts either "text" or "json".

flag.Parse()
logger := slogflags.Logger()
logger.Warn("This is not a drill", "key", "value", "etc", "etc)

Custom levels

If you define your own log levels, you can pass them to Logger using WithCustomLevels. Users can then specify them in the `log.level` flag.

Setting as the default logger

Pass WithSetDefault(true) when calling Logger to register the new instance as the default logger for log/slog. You can then call log/slog.Warn etc directly.

Redirecting old log calls

If your code or libraries use log rather than log/slog you can redirect them by setting a default logger as above. All log calls will be given the same log level, which you can alter using WithOldLogLevel. e.g.:

flag.Parse()
_ = slogflags.Logger(slogflags.WithSetDefault(true), slogflags.WithOldLogLevel(slog.LevelWarn))
log.Printf("hi")
// Prints: time=... level=WARN msg=hi

Other advanced usage

You can customise other behaviour of the created logger using WithDefaultLogLevel, WithWriter, WithAddSource and WithReplaceAttr. See the documentation for those funcs for more details.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Logger

func Logger(opts ...Option) *slog.Logger

Logger creates a new log/slog.Logger configured according to the options and flags.

flag.Parse must be called prior to calling this method.

Types

type Option

type Option func(*config)

func WithAddSource

func WithAddSource(addSource bool) Option

WithAddSource controls whether the source code location will be added to log lines. See log/slog.HandlerOptions.AddSource.

func WithCustomLevels

func WithCustomLevels(levels map[string]slog.Level) Option

WithCustomLevels adds extra levels to the defaults available in the `log.level` flag. The same level may be specified with multiple different keys to provide aliases.

The "level" attribute of log messages will automatically be rewritten if the level matches a custom attribute. If multiple aliases are defined for the same level, the alias that comes first lexicographically will be used.

func WithDefaultLogLevel

func WithDefaultLogLevel(level slog.Level) Option

WithDefaultLogLevel sets the default level that will be used if the `log.level` flag is not set. If not provided, the default is log/slog.LevelInfo.

func WithOldLogLevel

func WithOldLogLevel(level slog.Level) Option

WithOldLogLevel sets the level that should be used when interoping with the older log package. See log/slog.SetLogLoggerLevel. If not provided, the default is log/slog.LevelInfo.

func WithReplaceAttr

func WithReplaceAttr(fn func(groups []string, a slog.Attr) slog.Attr) Option

WithReplaceAttr allows setting an attribute replacement func on the logger. This can be used to rewrite attribute names or values. See log/slog.HandlerOptions.ReplaceAttr.

func WithSetDefault

func WithSetDefault(setDefault bool) Option

WithSetDefault sets whether the logger should be set as the default log/slog logger. See log/slog.SetDefault.

func WithWriter

func WithWriter(w io.Writer) Option

WithWriter sets a custom writer to be used for the log output. Defaults to os.Stdout.

Jump to

Keyboard shortcuts

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