Skip to content

Commit d2e4b69

Browse files
committed
add usage and credits sections to readme
1 parent c10da6c commit d2e4b69

1 file changed

Lines changed: 47 additions & 1 deletion

File tree

README.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,51 @@
11
# devlog
22

3-
A structured logging handler for Go, with a human-readable output format designed for development builds.
3+
A structured logging handler for Go, with a human-readable output format designed for development
4+
builds.
45

56
Run `go get hermannm.dev/devlog` to add it to your project!
7+
8+
## Usage
9+
10+
`devlog.Handler` implements [`slog.Handler`](https://pkg.go.dev/log/slog#Handler), so it can handle
11+
output for `slog`'s logging functions. It can be configured as follows:
12+
13+
```go
14+
logger := slog.New(devlog.NewHandler(os.Stdout, nil))
15+
slog.SetDefault(logger)
16+
```
17+
18+
Logging with `slog` will now use this handler:
19+
20+
```go
21+
slog.Warn("No value found for 'PORT' in env, defaulting to 8000")
22+
slog.Info("Server started", slog.Int("port", 8000), slog.String("environment", "DEV"))
23+
slog.Error(
24+
"Database query failed",
25+
slog.Group("dbError", slog.Int("code", 60), slog.String("message", "UNKNOWN_TABLE")),
26+
)
27+
```
28+
29+
...giving the following output (using a gruvbox terminal color scheme):
30+
31+
![Screenshot of 3 log messages in a terminal](https://github.com/hermannm/devlog/blob/assets/devlog-example-output.png?raw=true)
32+
33+
This output is meant to be easily read by a developer working locally. However, you may want a more
34+
structured format for production, such as JSON, to make log analysis easier. You can get both by
35+
conditionally choosing the log handler for your application, e.g.:
36+
37+
```go
38+
var handler slog.Handler
39+
switch os.Getenv("ENVIRONMENT") {
40+
case "PROD":
41+
handler = slog.NewJSONHandler(os.Stdout, nil)
42+
case "DEV":
43+
handler = devlog.NewHandler(os.Stdout, nil)
44+
}
45+
46+
slog.SetDefault(slog.New(handler))
47+
```
48+
49+
## Credits
50+
51+
- [Jonathan Amsterdam](https://github.com/jba) for his fantastic [Guide to Writing `slog` Handlers](https://github.com/golang/example/blob/1d6d2400d4027025cb8edc86a139c9c581d672f7/slog-handler-guide/README.md)

0 commit comments

Comments
 (0)