2026-08-15 02:30:36 +08:00
|
|
|
package logging
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
|
|
|
|
"strings"
|
|
|
|
|
"testing"
|
|
|
|
|
)
|
|
|
|
|
|
2026-08-17 10:10:14 +08:00
|
|
|
// TestLoggerWritesConsoleAndFile 验证日志同时写入控制台与文件,且包含消息与键值字段。
|
2026-08-15 02:30:36 +08:00
|
|
|
func TestLoggerWritesConsoleAndFile(t *testing.T) {
|
|
|
|
|
t.Parallel()
|
|
|
|
|
var console bytes.Buffer
|
|
|
|
|
path := filepath.Join(t.TempDir(), "daemon.log")
|
|
|
|
|
logger, closer, err := NewWithConsole(&console, path)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("create logger: %v", err)
|
|
|
|
|
}
|
|
|
|
|
logger.Info("transaction created", "transaction_id", "transaction-1")
|
|
|
|
|
if err := closer.Close(); err != nil {
|
|
|
|
|
t.Fatalf("close logger: %v", err)
|
|
|
|
|
}
|
|
|
|
|
fileContent, err := os.ReadFile(path)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("read log file: %v", err)
|
|
|
|
|
}
|
|
|
|
|
for name, content := range map[string]string{
|
|
|
|
|
"console": console.String(),
|
|
|
|
|
"file": string(fileContent),
|
|
|
|
|
} {
|
|
|
|
|
if !strings.Contains(content, "transaction created") || !strings.Contains(content, "transaction_id=transaction-1") {
|
|
|
|
|
t.Fatalf("%s log is missing fields: %q", name, content)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|