Sending Slack alerts only for golang errors that became 5xx responses
Our Slack error channel got an alert for every logged error, including the ones that ended as a 404. Here is how I hold Error logs until the request finishes and only post the ones that became a 5xx, using slog and plain net/http.
We added a Slack channel for API errors at work, and the first version was simple. Every Error() log call also posted to Slack. Six days later we rewrote it, because most of what landed in the channel wasn't a real problem.
See, the problem here is that a lot of Error() calls in a service layer are not server errors at all. A record that doesn't exist, a failed validation, a wrong password. The service logs it at error level, the handler maps it to a 404 or a 400, and the client gets exactly the answer it should. Nothing for a human to fix.
In this blog we will look at the fix we ended up with: hold every error log until the request is finished, then send them to Slack only if the final status code is 500 or above.
The idea
There are three pieces.
- A log handler that adds the user ID to every line and, for error level records, puts a copy into a queue that lives on the request context.
- A middleware that wraps the whole router. It records the status code, and when the handler returns it either drops the queue (2xx, 3xx, 4xx) or sends every queued alert to Slack (5xx).
- A small Slack client that posts to an incoming webhook.
At work we use zap and gin. For this post I wrote it again with log/slog and plain net/http so there are no dependencies at all. The method is the same. I built and tested everything on Go 1.27.3.
The log handler
slog makes this nicer than it was with zap, because a slog.Record already carries the program counter of the caller. So the alert can say which function logged the error without any runtime.Caller skip counting.
type Alert struct {
Msg string // message plus any error values
Function string // function that called slog
Stack string
UserID string
Details string // every attribute, one per line, sorted
}
type Handler struct {
inner slog.Handler
attrs []slog.Attr // from logger.With, so the alert sees them too
}
func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
r = r.Clone()
userID := userFrom(ctx)
if userID != "" {
r.AddAttrs(slog.String("user_id", userID))
}
if r.Level >= slog.LevelError {
if p, ok := ctx.Value(pendingKey{}).(*pending); ok {
p.add(h.newAlert(r, userID))
}
}
return h.inner.Handle(ctx, r)
}
The user ID is read from the context at the moment the line is logged. This one bit us. In our first version the logger was created at the start of the request with the user ID copied into it, but at that point the auth middleware hadn't run yet. So every alert came with a empty user ID. We fixed it with a closure that reads the user lazily. With slog and ErrorContext you get that for free, since the context you log with is the one auth already filled in.
WithAttrs and WithGroup must return the wrapper again, otherwise logger.With(...) silently drops you back to the plain handler and the alerts stop:
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
all := append(append([]slog.Attr{}, h.attrs...), attrs...)
return &Handler{inner: h.inner.WithAttrs(attrs), attrs: all}
}
func (h *Handler) WithGroup(name string) slog.Handler {
return &Handler{inner: h.inner.WithGroup(name), attrs: h.attrs}
}
(I keep groups flat in the alert. Good enough for a Slack message.)
Putting the details in the alert
Our first alerts carried only the message, like "upstream call failed". To find the status code and response body you had to open CloudWatch and search by request ID, even though those values were right there at the call site as log fields. A couple of months later we changed the alert to carry every field, and to append the text of any error value to the headline.
func (h *Handler) newAlert(r slog.Record, userID string) Alert {
fn := callerFunction(r.PC)
parts := []string{r.Message}
var details []string
collect := func(a slog.Attr) bool {
v := a.Value.Resolve()
if err, ok := v.Any().(error); ok && v.Kind() == slog.KindAny {
parts = append(parts, err.Error())
}
details = append(details, fmt.Sprintf("%s: %s", a.Key, v.String()))
return true
}
for _, a := range h.attrs {
collect(a)
}
r.Attrs(collect)
sort.Strings(details)
return Alert{
Msg: strings.Join(parts, " | "),
Function: fn,
Stack: trimStack(string(debug.Stack()), fn),
UserID: userID,
Details: strings.Join(details, "\n"),
}
}
func callerFunction(pc uintptr) string {
if pc == 0 {
return ""
}
frame, _ := runtime.CallersFrames([]uintptr{pc}).Next()
return frame.Function
}
Note the error check looks at the value type and ignores the key. People log errors as "err", "error", "cause", whatever they feel like that day. With zap we had the same issue with zap.NamedError, the first version looked for a field called error only and missed the rest.
debug.Stack() called from inside the handler starts with slog's own frames, which is useless noise on a phone screen. trimStack just finds the line that starts with the caller's function name and cuts everything above it:
func trimStack(stack, fn string) string {
if fn == "" {
return stack
}
lines := strings.Split(stack, "\n")
for i, l := range lines {
if strings.HasPrefix(l, fn+"(") {
return strings.Join(lines[i:], "\n")
}
}
return stack
}
The gate middleware
And now the part that actually kills the noise. The middleware creates the queue, records the status code, and decides after the handler returns.
func Gate(n Notifier, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, p := withPending(r.Context())
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
req := r.Method + " " + r.URL.Path
defer func() {
if v := recover(); v != nil {
if v == http.ErrAbortHandler {
panic(v)
}
send(n, "Panic", req, Alert{Msg: fmt.Sprint(v), Stack: string(debug.Stack())})
if !rec.wroteHeader {
http.Error(rec, "internal server error", http.StatusInternalServerError)
}
return
}
if rec.status < http.StatusInternalServerError {
p.drain() // 4xx and 2xx: the logs stay in the logs
return
}
for _, a := range p.drain() {
send(n, fmt.Sprintf("Error (%d)", rec.status), req, a)
}
}()
next.ServeHTTP(rec, r.WithContext(ctx))
})
}
A panic skips the queue and goes out straight away. There's no status to wait for, we are the ones deciding it is a 500.
send runs in a goroutine with a 10 second timeout, so a slow Slack never adds latency to the response. It logs failures with plain slog.Default(). If you use the alert logger there and Slack is down, you'd queue an alert about failing to send an alert. Not a fun loop.
The status recorder is the usual one:
type statusRecorder struct {
http.ResponseWriter
status int
wroteHeader bool
}
func (s *statusRecorder) WriteHeader(code int) {
if !s.wroteHeader {
s.status = code
s.wroteHeader = true
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Write(b []byte) (int, error) {
if !s.wroteHeader {
s.WriteHeader(http.StatusOK)
}
return s.ResponseWriter.Write(b)
}
Gate has to be the outermost middleware, before auth. If auth sits outside it, a 500 from inside auth has nowhere to queue.
The Slack client
An incoming webhook is enough. You create one in your Slack app settings and get a URL, keep it in an env var and never in the repo.
func (s *Slack) Notify(ctx context.Context, title, req string, a Alert) error {
user := a.UserID
if user == "" {
user = "anonymous"
}
text := fmt.Sprintf("*%s* `%s`\n*%s*\nuser: %s\nfunction: `%s`\n```%s```\n```%s```",
title, req, a.Msg, user, a.Function, a.Details, cut(a.Stack, 2500))
body, err := json.Marshal(map[string]string{"text": text})
if err != nil {
return err
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, s.WebhookURL, bytes.NewReader(body))
if err != nil {
return err
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := s.Client.Do(httpReq)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return fmt.Errorf("slack: %s: %s", resp.Status, msg)
}
return nil
}
I cut the stack at 2500 characters. A full goroutine stack from gin app is long and the useful part is at the top only.
Testing it
I wrote three tests against a fake notifier: a handler that logs an error and returns 404 must send nothing, the same handler returning 500 must send one alert, and a panic must send one alert. The 404 test waits 200 ms for an alert that should never come.
go test -race -v ./...
=== RUN TestNoAlertFor4xx
--- PASS: TestNoAlertFor4xx (0.20s)
=== RUN TestAlertFor5xx
gate_test.go:88: msg="find order failed | insert order\nsql: connection is already closed" function="example.com/alerts/alert.findOrder" user="user-42"
gate_test.go:89: details:
err: insert order
sql: connection is already closed
order_id: 17
user_id: user-42
--- PASS: TestAlertFor5xx (0.00s)
=== RUN TestPanicAlertsAtOnce
--- PASS: TestPanicAlertsAtOnce (0.00s)
The function name points at findOrder, which is the code that actually logged. The handler and middleware don't show up there. That's the bit I look at first when an alert comes in.
Things it doesn't do
A 503 that nobody logged at error level sends nothing, because the queue is empty. I'm basically fine with that, the load balancer metrics catch those. A request that logs three errors sends three messages. You could merge them into one message per request, I haven't needed it yet.
Background jobs have no request, so no queue, and their errors only go to the log. Where a job really needs a human, like a sweep that finds stuck records, we call the Slack client directly and send one alert per batch instead of one per item. Otherwise one bad upstream outage buries the channel again.
If you also want to stop secrets ending up in these alerts, see failing the golang build when someone logs a password or token with zap. An alert channel is just another place logs get copied to.
One last tip. We keep an admin only test route that sends a sample alert synchronously, with the details block filled in, and returns Slack's error if the post fails. After a new webhook or a token change I just call it once and look at the channel.