No description
Find a file
2025-11-26 12:10:35 +00:00
.github Dependencies: switch to weekly with cooldown 2025-11-26 12:10:35 +00:00
.gitignore Initial version 2025-05-07 16:52:08 +01:00
CHANGELOG.md Automatically rewrite log levels with custom names 2025-05-17 17:15:39 +01:00
doc.go Initial version 2025-05-07 16:52:08 +01:00
go.mod Bump github.com/stretchr/testify from 1.11.0 to 1.11.1 2025-08-28 07:09:09 +00:00
go.sum Bump github.com/stretchr/testify from 1.11.0 to 1.11.1 2025-08-28 07:09:09 +00:00
LICENCE Initial version 2025-05-07 16:52:08 +01:00
README.md Initial version 2025-05-07 16:52:08 +01:00
slogflags.go Automatically rewrite log levels with custom names 2025-05-17 17:15:39 +01:00
slogflags_test.go Automatically rewrite log levels with custom names 2025-05-17 17:15:39 +01:00

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.