Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vikstrous/slogevent
slogevent is a simplified (slow) API for integrating with slog
https://github.com/vikstrous/slogevent
Last synced: 19 days ago
JSON representation
slogevent is a simplified (slow) API for integrating with slog
- Host: GitHub
- URL: https://github.com/vikstrous/slogevent
- Owner: vikstrous
- License: mit
- Created: 2023-08-09T02:39:09.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2023-08-15T02:12:23.000Z (over 1 year ago)
- Last Synced: 2025-01-02T03:42:17.740Z (23 days ago)
- Language: Go
- Size: 8.79 KB
- Stars: 3
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# slogevent
[![Go Reference](https://pkg.go.dev/badge/github.com/vikstrous/slogevent.svg)](https://pkg.go.dev/github.com/vikstrous/slogevent)
slogevent is a simplified API for integrating with slog.
Add `slogevent` as a dependency by running:
```sh
go get github.com/vikstrous/slogevent
```Writing a handler for Go's standard library [log/slog](https://pkg.go.dev/log/slog) package is hard for good reasons. See the details for how to do that [here](https://golang.org/s/slog-handler-guide). However, sometimes there's a need to simply trigger an event when certain logs are written and this should be easy.
This package provides the missing glue to allow you to write log handlers like this:
```go
func EventHandler(ctx context.Context, e slogevent.Event) {
if e.Level >= slog.LevelError {
attrs, _ := json.Marshal(e.Attrs)
SoundTheAlarm(e.Message, string(attrs))
}
}
```To use this custom even handler with `slog`, pass it into slog as a handler when creating your logger, like this:
```go
slogLogger := slog.New(slogevent.NewHandler(EventHandler, slog.NewTextHandler(os.Stderr, nil)))
```There's a more detailed example in the [slogexamples](https://github.com/vikstrous/slogexamples) repo along with other examples of how to extend slog without writing a handler.
slogevent acts as a wrapper for whatever handler you would normally use and fires your event before the next handler runs. It takes care of the annoying glue code needed to collect attrs and groups when `With()` and `WithGroup()` are used and converts all groups into a flag list of `slog.Attr`s that you can use without much effort.
This package is pre-v1 and the API may change. Please provide feedback about the API in the issues and let me know how I can make your slogging easier :muscle: