59 lines
1.8 KiB
Go
59 lines
1.8 KiB
Go
package logging
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestZapHandlerHonorsConfiguredLevel(t *testing.T) {
|
|
root := t.TempDir()
|
|
handler, cleanup := newZapHandler(root, "application.log", Options{Level: "error", Format: "json"})
|
|
defer cleanup()
|
|
|
|
if handler.Enabled(context.Background(), slog.LevelInfo) {
|
|
t.Fatal("info should be disabled when level is error")
|
|
}
|
|
if !handler.Enabled(context.Background(), slog.LevelError) {
|
|
t.Fatal("error should be enabled when level is error")
|
|
}
|
|
}
|
|
|
|
func TestZapHandlerUsesDebugFallbackForInvalidLevel(t *testing.T) {
|
|
root := t.TempDir()
|
|
handler, cleanup := newZapHandler(root, "application.log", Options{Level: "not-a-level", Format: "json"})
|
|
defer cleanup()
|
|
|
|
if !handler.Enabled(context.Background(), slog.LevelDebug) {
|
|
t.Fatal("invalid levels should use the reference debug fallback")
|
|
}
|
|
}
|
|
|
|
func TestZapHandlerRoutesHTTPAndErrorLogs(t *testing.T) {
|
|
root := t.TempDir()
|
|
handler, cleanup := newZapHandler(root, "application.log", Options{Level: "info", Format: "json"})
|
|
logger := slog.New(handler)
|
|
logger.Info("request", "mod", "http", "request_id", "req-1")
|
|
logger.Error("failed", "mod", "users")
|
|
cleanup()
|
|
|
|
dateEntries, err := os.ReadDir(root)
|
|
if err != nil || len(dateEntries) != 1 {
|
|
t.Fatalf("expected one daily log directory, entries=%v err=%v", len(dateEntries), err)
|
|
}
|
|
date := dateEntries[0].Name()
|
|
paths := []string{
|
|
filepath.Join(root, date, "application.log"),
|
|
filepath.Join(root, date, "http", "access.log"),
|
|
filepath.Join(root, date, "users", "application.log"),
|
|
filepath.Join(root, date, "error", "error.log"),
|
|
}
|
|
for _, path := range paths {
|
|
if info, err := os.Stat(path); err != nil || info.Size() == 0 {
|
|
t.Fatalf("expected non-empty routed log %s: info=%v err=%v", path, info, err)
|
|
}
|
|
}
|
|
}
|