Explore documentation
Better Stack Go logging
Start logging in 2 steps
Collect logs from your Go application.
1. Install
Add slog-betterstack to your project dependencies using go get
.
Install the samber/slog-betterstack package
go get github.com/samber/slog-betterstack
2. Set up handler and start logging 🎉
Configure slog-betterstack
as a handler in a new slog
logger.
Your log events will be sent to Better Stack automatically.
Logging using samber/slog-betterstack
import (
slogbetterstack "github.com/samber/slog-betterstack"
"log/slog"
)
func main() {
logger := slog.New(slogbetterstack.Option{Token: "$SOURCE_TOKEN"}.NewBetterstackHandler())
// Logger is ready to be used
logger.Info("Hello from Better Stack!")
}
You should see your logs in Better Stack → Live tail.
Huge thanks to Samuel Berthe who maintains the slog-betterstack library as an MIT-licensed open-source! ❤️
Context and structured data
You can use structured data in slog and send context along with your logs.
For more details check out the slog official documentation.
Logging with context in slog
import (
"fmt"
"net/http"
"time"
slogbetterstack "github.com/samber/slog-betterstack"
"log/slog"
)
func main() {
logger := slog.New(
slogbetterstack.Option{
Level: slog.LevelDebug,
Token: "$SOURCE_TOKEN",
}.NewBetterstackHandler(),
)
// You can add common context
logger = logger.With("release", "v1.0.0")
// Log a debug message
logger.Debug("Debugging user service.", "service", "UserService")
// You can add the context using With
logger.With("userID", 123).Error("Unable to fetch user data.")
// Or use structured data
logger.
With(
slog.Group("user",
slog.String("id", "user-123"),
slog.Time("created_at", time.Now()),
),
).
With("error", fmt.Errorf("an error")).
Error("a message", slog.Int("count", 1))
}
Need help?
Please reach out to us at hello@betterstack.com.
We're happy to help! 🙏