feat: complete API-driven projects with infrastructure and business acceptance
This commit is contained in:
157
logx/production_test.go
Normal file
157
logx/production_test.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package logx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type credentialsValue struct{}
|
||||
|
||||
func (credentialsValue) LogValue() slog.Value {
|
||||
return slog.GroupValue(slog.String("token", "do-not-print"), slog.String("label", "keep"))
|
||||
}
|
||||
func TestStructuredRedaction(t *testing.T) {
|
||||
for _, format := range []string{"json", "text"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
logger, err := New(Config{Writer: &out, Format: format, RedactKeys: []string{"bankAccount"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer logger.Close()
|
||||
type account struct {
|
||||
Name string `json:"name"`
|
||||
Password string `json:"password"`
|
||||
Account string `json:"bankAccount"`
|
||||
}
|
||||
nested := map[string]any{"profile": account{"visible", "do-not-print", "do-not-print"}, "Authorization": "do-not-print", "items": []any{map[string]string{"API_KEY": "do-not-print", "label": "visible"}}}
|
||||
logger.With("refreshToken", "do-not-print").WithGroup("metadata").Info("event", "body", nested, slog.Group("password", "value", "do-not-print"), "valuer", credentialsValue{})
|
||||
if strings.Contains(out.String(), "do-not-print") || !strings.Contains(out.String(), "visible") || !strings.Contains(out.String(), redacted) {
|
||||
t.Fatal(out.String())
|
||||
}
|
||||
if format == "json" {
|
||||
var value map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestRedactionDoesNotMutateOrLoop(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
logger, _ := New(Config{Writer: &out})
|
||||
m := map[string]any{"password": "original"}
|
||||
m["self"] = m
|
||||
logger.Info("event", "map", m)
|
||||
if m["password"] != "original" || strings.Contains(out.String(), "original") || !strings.Contains(out.String(), "TRUNCATED") {
|
||||
t.Fatal(out.String())
|
||||
}
|
||||
}
|
||||
func TestRotationCompressRetentionAndClose(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "logs", "app.log")
|
||||
logger, err := New(Config{File: file, Rotation: RotationConfig{Enabled: true, MaxSizeMB: 1, MaxBackups: 2, MaxAgeDays: 1, Compress: true}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := strings.Repeat("x", 600<<10)
|
||||
for i := 0; i < 5; i++ {
|
||||
logger.Info("rotation", "value", payload)
|
||||
time.Sleep(3 * time.Millisecond)
|
||||
}
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
var backups []string
|
||||
for time.Now().Before(deadline) {
|
||||
backups, _ = filepath.Glob(filepath.Join(dir, "logs", "app-*.gz"))
|
||||
plain, _ := filepath.Glob(filepath.Join(dir, "logs", "app-*.log"))
|
||||
if len(backups) == 2 && len(plain) == 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if len(backups) != 2 {
|
||||
t.Fatalf("backups: %v", backups)
|
||||
}
|
||||
for _, path := range backups {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
z, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := io.ReadAll(z)
|
||||
z.Close()
|
||||
f.Close()
|
||||
if err != nil || !json.Valid(bytes.TrimSpace(data)) {
|
||||
t.Fatal("corrupt backup", err)
|
||||
}
|
||||
}
|
||||
child := logger.With("component", "test")
|
||||
if err = logger.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _ := os.Stat(file)
|
||||
child.Info("must not reopen")
|
||||
after, _ := os.Stat(file)
|
||||
if before.Size() != after.Size() {
|
||||
t.Fatal("closed logger wrote")
|
||||
}
|
||||
}
|
||||
func TestRotationConcurrentWritesAndValidation(t *testing.T) {
|
||||
for _, cfg := range []Config{{Rotation: RotationConfig{Enabled: true}}, {File: "unused", Writer: io.Discard, Rotation: RotationConfig{Enabled: true}}, {Rotation: RotationConfig{MaxBackups: -1}}} {
|
||||
if _, err := New(cfg); err == nil {
|
||||
t.Fatal("invalid rotation accepted")
|
||||
}
|
||||
}
|
||||
file := filepath.Join(t.TempDir(), "app.log")
|
||||
logger, err := New(Config{File: file, Rotation: RotationConfig{Enabled: true}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 100; j++ {
|
||||
logger.Info("concurrent", "n", j)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
logger.Close()
|
||||
raw, _ := os.ReadFile(file)
|
||||
if len(bytes.Split(bytes.TrimSpace(raw), []byte("\n"))) != 800 {
|
||||
t.Fatal("lost logs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusinessErrorStack(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
logger, _ := New(Config{Writer: &out, AddSource: true})
|
||||
ctx := WithRequestID(context.Background(), "request")
|
||||
logger.ErrorStackContext(ctx, "failure", "password", "do-not-print")
|
||||
var entry map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &entry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(entry["stack"].(string), "TestBusinessErrorStack") || entry["requestId"] != "request" || strings.Contains(out.String(), "do-not-print") {
|
||||
t.Fatal(out.String())
|
||||
}
|
||||
if entry["source"].(map[string]any)["file"] == nil {
|
||||
t.Fatal("source schema changed")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user