mirror of
https://github.com/taigrr/log-socket
synced 2026-03-20 16:02:28 -07:00
Compare commits
1 Commits
cd/ws-test
...
burrow/6-a
| Author | SHA1 | Date | |
|---|---|---|---|
| 4d74b0a950 |
13
.github/workflows/ci.yaml
vendored
13
.github/workflows/ci.yaml
vendored
@@ -1,20 +1,23 @@
|
|||||||
name: Go package
|
name: Go package
|
||||||
|
|
||||||
on: [push, pull_request]
|
on: [push]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: "1.26"
|
go-version: "1.25"
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: go get .
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: go build -v ./...
|
run: go build -v ./...
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: go test -race -v ./...
|
run: go test -v ./...
|
||||||
|
|||||||
23
CRUSH.md
23
CRUSH.md
@@ -239,7 +239,7 @@ Still embeds viewer.html, but HTML now includes:
|
|||||||
|
|
||||||
## Go Version & Dependencies
|
## Go Version & Dependencies
|
||||||
|
|
||||||
- **Go version**: 1.26.1 (specified in go.mod)
|
- **Go version**: 1.24.4 (specified in go.mod)
|
||||||
- **Only external dependency**: `github.com/gorilla/websocket v1.5.3`
|
- **Only external dependency**: `github.com/gorilla/websocket v1.5.3`
|
||||||
|
|
||||||
## Naming Conventions & Style
|
## Naming Conventions & Style
|
||||||
@@ -314,17 +314,27 @@ UI provides "Reconnect" button for this purpose.
|
|||||||
### 6. Stderr Client Uses All Namespaces
|
### 6. Stderr Client Uses All Namespaces
|
||||||
The built-in stderr client (created in `init()`) listens to all namespaces:
|
The built-in stderr client (created in `init()`) listens to all namespaces:
|
||||||
```go
|
```go
|
||||||
stderrClient = CreateClient() // No args = all namespaces
|
stderrClient = CreateClient(DefaultNamespace)
|
||||||
```
|
```
|
||||||
|
|
||||||
It prints logs matching its level and namespace filter in `logStdErr()`:
|
But only prints logs matching its own namespace in `logStdErr()`:
|
||||||
```go
|
```go
|
||||||
if e.level >= c.LogLevel && c.matchesNamespace(e.Namespace) {
|
if e.level >= c.LogLevel && c.matchesNamespace(e.Namespace) {
|
||||||
fmt.Fprintf(os.Stderr, "%s\t%s\t[%s]\t%s\t%s\n", ...)
|
fmt.Fprintf(os.Stderr, "%s\t%s\t[%s]\t%s\t%s\n", ...)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Since `CreateClient()` is called with no arguments, the Namespaces slice is empty, which means it matches all namespaces.
|
**Wait, that's a bug!** The stderr client is created with `DefaultNamespace` but should be created with no namespaces to see all logs. Let me check this.
|
||||||
|
|
||||||
|
Actually looking at the code:
|
||||||
|
```go
|
||||||
|
stderrClient = CreateClient(DefaultNamespace)
|
||||||
|
```
|
||||||
|
|
||||||
|
This means stderr client only sees "default" namespace logs. This might be intentional, but seems like a bug. Should probably be:
|
||||||
|
```go
|
||||||
|
stderrClient = CreateClient() // No args = all namespaces
|
||||||
|
```
|
||||||
|
|
||||||
### 7. Grid Layout Updated
|
### 7. Grid Layout Updated
|
||||||
The log viewer grid changed from 4 to 5 columns:
|
The log viewer grid changed from 4 to 5 columns:
|
||||||
@@ -364,9 +374,8 @@ All existing tests pass with namespace support added.
|
|||||||
## CI/CD
|
## CI/CD
|
||||||
|
|
||||||
GitHub Actions workflow (`.github/workflows/ci.yaml`):
|
GitHub Actions workflow (`.github/workflows/ci.yaml`):
|
||||||
- Uses Go 1.26, actions/checkout@v4, actions/setup-go@v5
|
- Still uses Go 1.21 (should update to 1.24.4 to match go.mod)
|
||||||
- Runs tests with `-race` flag
|
- No changes needed for v2 functionality
|
||||||
- Triggers on push and pull_request
|
|
||||||
|
|
||||||
## Common Tasks
|
## Common Tasks
|
||||||
|
|
||||||
|
|||||||
35
README.md
35
README.md
@@ -15,7 +15,6 @@ A real-time log viewer with WebSocket support and namespace filtering, written i
|
|||||||
- **Namespace filtering**: Subscribe to specific namespaces via WebSocket
|
- **Namespace filtering**: Subscribe to specific namespaces via WebSocket
|
||||||
- **Frontend namespace selector**: Filter logs by namespace in the web UI
|
- **Frontend namespace selector**: Filter logs by namespace in the web UI
|
||||||
- **Namespace API**: GET `/api/namespaces` to list all active namespaces
|
- **Namespace API**: GET `/api/namespaces` to list all active namespaces
|
||||||
- **Colored terminal output**: Log levels are color-coded in terminal (no external packages)
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@@ -189,40 +188,6 @@ ws://localhost:8080/ws?namespaces=api,database # Multiple namespaces
|
|||||||
- **Color Coding**: Different log levels are color-coded
|
- **Color Coding**: Different log levels are color-coded
|
||||||
- **Reconnect**: Reconnect WebSocket with new namespace filter
|
- **Reconnect**: Reconnect WebSocket with new namespace filter
|
||||||
|
|
||||||
## Terminal Colors
|
|
||||||
|
|
||||||
Log output to stderr is automatically colorized when writing to a terminal. Colors are disabled when output is piped or redirected to a file.
|
|
||||||
|
|
||||||
### Color Scheme
|
|
||||||
|
|
||||||
| Level | Color |
|
|
||||||
|--------|--------------|
|
|
||||||
| TRACE | Gray |
|
|
||||||
| DEBUG | Cyan |
|
|
||||||
| INFO | Green |
|
|
||||||
| NOTICE | Blue |
|
|
||||||
| WARN | Yellow |
|
|
||||||
| ERROR | Red |
|
|
||||||
| PANIC | Bold Red |
|
|
||||||
| FATAL | Bold Red |
|
|
||||||
|
|
||||||
### Controlling Colors
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Disable colors (e.g., for CI/CD or file output)
|
|
||||||
logger.SetColorEnabled(false)
|
|
||||||
|
|
||||||
// Enable colors explicitly
|
|
||||||
logger.SetColorEnabled(true)
|
|
||||||
|
|
||||||
// Check current state
|
|
||||||
if logger.ColorEnabled() {
|
|
||||||
// colors are on
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Colors are implemented using standard ANSI escape codes with no external dependencies.
|
|
||||||
|
|
||||||
## Migration from v1
|
## Migration from v1
|
||||||
|
|
||||||
### Import Path
|
### Import Path
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
package browser
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestLogSocketViewHandler_HTTP(t *testing.T) {
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
LogSocketViewHandler(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
body := w.Body.String()
|
|
||||||
// html/template escapes forward slashes in JS context
|
|
||||||
if !strings.Contains(body, `ws:\/\/localhost:8080\/ws`) {
|
|
||||||
t.Error("response should contain escaped ws://localhost:8080/ws URL")
|
|
||||||
}
|
|
||||||
if !strings.Contains(body, "<!DOCTYPE html>") {
|
|
||||||
t.Error("response should contain HTML doctype")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLogSocketViewHandler_CustomPath(t *testing.T) {
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "http://myhost:9090/dashboard/", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
LogSocketViewHandler(w, req)
|
|
||||||
|
|
||||||
body := w.Body.String()
|
|
||||||
if !strings.Contains(body, `ws:\/\/myhost:9090\/dashboard\/ws`) {
|
|
||||||
t.Error("expected escaped ws://myhost:9090/dashboard/ws in body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLogSocketViewHandler_TrailingSlashTrimmed(t *testing.T) {
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
LogSocketViewHandler(w, req)
|
|
||||||
|
|
||||||
body := w.Body.String()
|
|
||||||
// Should NOT have double slash before ws
|
|
||||||
if strings.Contains(body, `\/\/ws`) {
|
|
||||||
t.Error("should not have double slash before /ws")
|
|
||||||
}
|
|
||||||
if !strings.Contains(body, `ws:\/\/example.com\/ws`) {
|
|
||||||
t.Error("expected escaped ws://example.com/ws in body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
// Example: basic usage of log-socket as a drop-in logger.
|
|
||||||
//
|
|
||||||
// This demonstrates using the package-level logging functions,
|
|
||||||
// which work similarly to the standard library's log package.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/taigrr/log-socket/v2/browser"
|
|
||||||
logger "github.com/taigrr/log-socket/v2/log"
|
|
||||||
"github.com/taigrr/log-socket/v2/ws"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
defer logger.Flush()
|
|
||||||
|
|
||||||
// Set the minimum log level (default is LTrace, showing everything)
|
|
||||||
logger.SetLogLevel(logger.LDebug)
|
|
||||||
|
|
||||||
// Package-level functions log to the "default" namespace
|
|
||||||
logger.Info("Application starting up")
|
|
||||||
logger.Debug("Debug mode enabled")
|
|
||||||
logger.Warnf("Config file not found at %s, using defaults", "/etc/app/config.yaml")
|
|
||||||
logger.Errorf("Failed to connect to database: %s", "connection refused")
|
|
||||||
|
|
||||||
// Print/Printf/Println are aliases for Info
|
|
||||||
logger.Println("This is equivalent to Infoln")
|
|
||||||
|
|
||||||
// Start the web UI so you can view logs at http://localhost:8080
|
|
||||||
http.HandleFunc("/ws", ws.LogSocketHandler)
|
|
||||||
http.HandleFunc("/", browser.LogSocketViewHandler)
|
|
||||||
fmt.Println("Log viewer available at http://localhost:8080")
|
|
||||||
logger.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
// Example: programmatic log client with namespace filtering.
|
|
||||||
//
|
|
||||||
// This shows how to create a Client that receives log entries
|
|
||||||
// programmatically, optionally filtered to specific namespaces.
|
|
||||||
// Useful for building custom log processors, alerting, or forwarding.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
logger "github.com/taigrr/log-socket/v2/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
defer logger.Flush()
|
|
||||||
|
|
||||||
// Create a client that receives ALL log entries
|
|
||||||
allLogs := logger.CreateClient()
|
|
||||||
allLogs.SetLogLevel(logger.LInfo)
|
|
||||||
|
|
||||||
// Create a client that only receives "database" and "auth" logs
|
|
||||||
securityLogs := logger.CreateClient("database", "auth")
|
|
||||||
securityLogs.SetLogLevel(logger.LWarn) // Only warnings and above
|
|
||||||
|
|
||||||
dbLog := logger.NewLogger("database")
|
|
||||||
authLog := logger.NewLogger("auth")
|
|
||||||
apiLog := logger.NewLogger("api")
|
|
||||||
|
|
||||||
// Process all logs
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
entry := allLogs.Get()
|
|
||||||
fmt.Printf("[ALL] %s [%s] %s: %s\n",
|
|
||||||
entry.Timestamp.Format(time.TimeOnly),
|
|
||||||
entry.Namespace, entry.Level, entry.Output)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Process only security-relevant warnings/errors
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
entry := securityLogs.Get()
|
|
||||||
if entry.Level == "ERROR" || entry.Level == "WARN" {
|
|
||||||
fmt.Printf("🚨 SECURITY ALERT [%s] %s: %s\n",
|
|
||||||
entry.Namespace, entry.Level, entry.Output)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Generate some logs
|
|
||||||
for i := 0; i < 5; i++ {
|
|
||||||
apiLog.Info("API request processed")
|
|
||||||
dbLog.Info("Query executed successfully")
|
|
||||||
dbLog.Warn("Connection pool running low")
|
|
||||||
authLog.Error("Brute force attempt detected")
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up clients when done
|
|
||||||
allLogs.Destroy()
|
|
||||||
securityLogs.Destroy()
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
// Example: log level filtering and all available levels.
|
|
||||||
//
|
|
||||||
// log-socket supports 8 log levels from TRACE (most verbose)
|
|
||||||
// to FATAL (least verbose). Setting a log level filters out
|
|
||||||
// everything below it.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
logger "github.com/taigrr/log-socket/v2/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
defer logger.Flush()
|
|
||||||
|
|
||||||
fmt.Println("=== All log levels (TRACE and above) ===")
|
|
||||||
logger.SetLogLevel(logger.LTrace)
|
|
||||||
|
|
||||||
logger.Trace("Detailed execution trace — variable x = 42")
|
|
||||||
logger.Debug("Processing request for user_id=123")
|
|
||||||
logger.Info("Server started on :8080")
|
|
||||||
logger.Notice("Configuration reloaded")
|
|
||||||
logger.Warn("Disk usage at 85%")
|
|
||||||
logger.Error("Failed to send email: SMTP timeout")
|
|
||||||
// logger.Panic("...") — would panic
|
|
||||||
// logger.Fatal("...") — would os.Exit(1)
|
|
||||||
|
|
||||||
fmt.Println("\n=== Formatted variants ===")
|
|
||||||
logger.Infof("Request took %dms", 42)
|
|
||||||
logger.Warnf("Retrying in %d seconds (attempt %d/%d)", 5, 2, 3)
|
|
||||||
logger.Errorf("HTTP %d: %s", 503, "Service Unavailable")
|
|
||||||
|
|
||||||
fmt.Println("\n=== Only WARN and above ===")
|
|
||||||
logger.SetLogLevel(logger.LWarn)
|
|
||||||
|
|
||||||
logger.Debug("This will NOT appear")
|
|
||||||
logger.Info("This will NOT appear either")
|
|
||||||
logger.Warn("This WILL appear")
|
|
||||||
logger.Error("This WILL appear too")
|
|
||||||
|
|
||||||
fmt.Println("\n=== Per-logger levels via namespaced loggers ===")
|
|
||||||
logger.SetLogLevel(logger.LTrace) // Reset global
|
|
||||||
|
|
||||||
appLog := logger.NewLogger("app")
|
|
||||||
appLog.Info("Namespaced loggers inherit the global output but tag entries")
|
|
||||||
appLog.Warnf("Something needs attention in the %s subsystem", "app")
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
// Example: namespace-based logging for organizing logs by component.
|
|
||||||
//
|
|
||||||
// Namespaces let you tag log entries by subsystem (api, database, auth, etc.)
|
|
||||||
// and filter them in the web UI or via programmatic clients.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/taigrr/log-socket/v2/browser"
|
|
||||||
logger "github.com/taigrr/log-socket/v2/log"
|
|
||||||
"github.com/taigrr/log-socket/v2/ws"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
defer logger.Flush()
|
|
||||||
|
|
||||||
// Create loggers for different subsystems
|
|
||||||
apiLog := logger.NewLogger("api")
|
|
||||||
dbLog := logger.NewLogger("database")
|
|
||||||
authLog := logger.NewLogger("auth")
|
|
||||||
cacheLog := logger.NewLogger("cache")
|
|
||||||
|
|
||||||
// Simulate application activity
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
apiLog.Infof("GET /api/users — 200 OK (%dms)", rand.Intn(200))
|
|
||||||
apiLog.Debugf("Request headers: Accept=application/json")
|
|
||||||
time.Sleep(1 * time.Second)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
dbLog.Infof("SELECT * FROM users — %d rows", rand.Intn(100))
|
|
||||||
if rand.Float64() < 0.3 {
|
|
||||||
dbLog.Warn("Slow query detected (>500ms)")
|
|
||||||
}
|
|
||||||
time.Sleep(2 * time.Second)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
if rand.Float64() < 0.7 {
|
|
||||||
authLog.Info("User login successful")
|
|
||||||
} else {
|
|
||||||
authLog.Error("Failed login attempt from 192.168.1.42")
|
|
||||||
}
|
|
||||||
time.Sleep(3 * time.Second)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
cacheLog.Tracef("Cache hit ratio: %.1f%%", rand.Float64()*100)
|
|
||||||
if rand.Float64() < 0.1 {
|
|
||||||
cacheLog.Warn("Cache eviction triggered")
|
|
||||||
}
|
|
||||||
time.Sleep(5 * time.Second)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// The /api/namespaces endpoint lists all active namespaces
|
|
||||||
http.HandleFunc("/ws", ws.LogSocketHandler)
|
|
||||||
http.HandleFunc("/api/namespaces", ws.NamespacesHandler)
|
|
||||||
http.HandleFunc("/", browser.LogSocketViewHandler)
|
|
||||||
fmt.Println("Log viewer with namespace filtering at http://localhost:8080")
|
|
||||||
logger.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
|
|
||||||
}
|
|
||||||
2
go.mod
2
go.mod
@@ -1,5 +1,5 @@
|
|||||||
module github.com/taigrr/log-socket/v2
|
module github.com/taigrr/log-socket/v2
|
||||||
|
|
||||||
go 1.26.1
|
go 1.25.4
|
||||||
|
|
||||||
require github.com/gorilla/websocket v1.5.3
|
require github.com/gorilla/websocket v1.5.3
|
||||||
|
|||||||
99
log/color.go
99
log/color.go
@@ -1,99 +0,0 @@
|
|||||||
package log
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ANSI color codes for terminal output
|
|
||||||
const (
|
|
||||||
colorReset = "\033[0m"
|
|
||||||
colorRed = "\033[31m"
|
|
||||||
colorGreen = "\033[32m"
|
|
||||||
colorYellow = "\033[33m"
|
|
||||||
colorBlue = "\033[34m"
|
|
||||||
colorPurple = "\033[35m"
|
|
||||||
colorCyan = "\033[36m"
|
|
||||||
colorWhite = "\033[37m"
|
|
||||||
colorGray = "\033[90m"
|
|
||||||
|
|
||||||
// Bold variants
|
|
||||||
colorBoldRed = "\033[1;31m"
|
|
||||||
colorBoldYellow = "\033[1;33m"
|
|
||||||
colorBoldWhite = "\033[1;37m"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
colorEnabled = true
|
|
||||||
colorEnabledOnce sync.Once
|
|
||||||
colorMux sync.RWMutex
|
|
||||||
)
|
|
||||||
|
|
||||||
// SetColorEnabled enables or disables colored output for stderr logging.
|
|
||||||
// By default, color is enabled when stderr is a terminal.
|
|
||||||
func SetColorEnabled(enabled bool) {
|
|
||||||
colorMux.Lock()
|
|
||||||
colorEnabled = enabled
|
|
||||||
colorMux.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ColorEnabled returns whether colored output is currently enabled.
|
|
||||||
func ColorEnabled() bool {
|
|
||||||
colorMux.RLock()
|
|
||||||
defer colorMux.RUnlock()
|
|
||||||
return colorEnabled
|
|
||||||
}
|
|
||||||
|
|
||||||
// isTerminal checks if the given file descriptor is a terminal.
|
|
||||||
// This is a simple heuristic that works on Unix-like systems.
|
|
||||||
func isTerminal(f *os.File) bool {
|
|
||||||
stat, err := f.Stat()
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return (stat.Mode() & os.ModeCharDevice) != 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// initColorEnabled sets the default color state based on whether stderr is a terminal.
|
|
||||||
func initColorEnabled() {
|
|
||||||
colorEnabledOnce.Do(func() {
|
|
||||||
colorEnabled = isTerminal(os.Stderr)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// levelColor returns the ANSI color code for a given log level.
|
|
||||||
func levelColor(level Level) string {
|
|
||||||
switch level {
|
|
||||||
case LTrace:
|
|
||||||
return colorGray
|
|
||||||
case LDebug:
|
|
||||||
return colorCyan
|
|
||||||
case LInfo:
|
|
||||||
return colorGreen
|
|
||||||
case LNotice:
|
|
||||||
return colorBlue
|
|
||||||
case LWarn:
|
|
||||||
return colorYellow
|
|
||||||
case LError:
|
|
||||||
return colorRed
|
|
||||||
case LPanic:
|
|
||||||
return colorBoldRed
|
|
||||||
case LFatal:
|
|
||||||
return colorBoldRed
|
|
||||||
default:
|
|
||||||
return colorReset
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// colorize wraps text with ANSI color codes if color is enabled.
|
|
||||||
func colorize(text string, color string) string {
|
|
||||||
if !ColorEnabled() {
|
|
||||||
return text
|
|
||||||
}
|
|
||||||
return color + text + colorReset
|
|
||||||
}
|
|
||||||
|
|
||||||
// colorizeLevelText returns the level string with appropriate color.
|
|
||||||
func colorizeLevelText(level string, lvl Level) string {
|
|
||||||
return colorize(level, levelColor(lvl))
|
|
||||||
}
|
|
||||||
61
log/log.go
61
log/log.go
@@ -22,8 +22,7 @@ var (
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
namespaces = make(map[string]bool)
|
namespaces = make(map[string]bool)
|
||||||
initColorEnabled()
|
stderrClient = CreateClient(DefaultNamespace)
|
||||||
stderrClient = CreateClient()
|
|
||||||
stderrClient.SetLogLevel(LTrace)
|
stderrClient.SetLogLevel(LTrace)
|
||||||
stderrFinished = make(chan bool, 1)
|
stderrFinished = make(chan bool, 1)
|
||||||
go stderrClient.logStdErr()
|
go stderrClient.logStdErr()
|
||||||
@@ -32,10 +31,7 @@ func init() {
|
|||||||
func (c *Client) logStdErr() {
|
func (c *Client) logStdErr() {
|
||||||
for e := range c.writer {
|
for e := range c.writer {
|
||||||
if e.level >= c.LogLevel && c.matchesNamespace(e.Namespace) {
|
if e.level >= c.LogLevel && c.matchesNamespace(e.Namespace) {
|
||||||
levelStr := colorizeLevelText(e.Level, e.level)
|
fmt.Fprintf(os.Stderr, "%s\t%s\t[%s]\t%s\t%s\n", e.Timestamp.String(), e.Level, e.Namespace, e.Output, e.File)
|
||||||
nsStr := colorize("["+e.Namespace+"]", colorPurple)
|
|
||||||
fileStr := colorize(e.File, colorGray)
|
|
||||||
fmt.Fprintf(os.Stderr, "%s\t%s\t%s\t%s\t%s\n", e.Timestamp.String(), levelStr, nsStr, e.Output, fileStr)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
stderrFinished <- true
|
stderrFinished <- true
|
||||||
@@ -74,19 +70,19 @@ func Flush() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) Destroy() error {
|
func (c *Client) Destroy() error {
|
||||||
|
var otherClients []*Client
|
||||||
if !c.initialized {
|
if !c.initialized {
|
||||||
panic(errors.New("cannot delete uninitialized client, did you use CreateClient?"))
|
panic(errors.New("cannot delete uninitialized client, did you use CreateClient?"))
|
||||||
}
|
}
|
||||||
sliceTex.Lock()
|
sliceTex.Lock()
|
||||||
|
c.writer = nil
|
||||||
c.initialized = false
|
c.initialized = false
|
||||||
var otherClients []*Client
|
|
||||||
for _, x := range clients {
|
for _, x := range clients {
|
||||||
if x != c && x.initialized {
|
if x.initialized {
|
||||||
otherClients = append(otherClients, x)
|
otherClients = append(otherClients, x)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
clients = otherClients
|
clients = otherClients
|
||||||
c.writer = nil
|
|
||||||
sliceTex.Unlock()
|
sliceTex.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -103,13 +99,10 @@ func createLog(e Entry) {
|
|||||||
namespacesMux.Lock()
|
namespacesMux.Lock()
|
||||||
namespaces[e.Namespace] = true
|
namespaces[e.Namespace] = true
|
||||||
namespacesMux.Unlock()
|
namespacesMux.Unlock()
|
||||||
|
|
||||||
sliceTex.Lock()
|
sliceTex.Lock()
|
||||||
for _, c := range clients {
|
for _, c := range clients {
|
||||||
func(c *Client, e Entry) {
|
func(c *Client, e Entry) {
|
||||||
if c.writer == nil || !c.initialized {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Filter by namespace if client has filters specified
|
// Filter by namespace if client has filters specified
|
||||||
if !c.matchesNamespace(e.Namespace) {
|
if !c.matchesNamespace(e.Namespace) {
|
||||||
return
|
return
|
||||||
@@ -133,7 +126,7 @@ func createLog(e Entry) {
|
|||||||
func GetNamespaces() []string {
|
func GetNamespaces() []string {
|
||||||
namespacesMux.RLock()
|
namespacesMux.RLock()
|
||||||
defer namespacesMux.RUnlock()
|
defer namespacesMux.RUnlock()
|
||||||
|
|
||||||
result := make([]string, 0, len(namespaces))
|
result := make([]string, 0, len(namespaces))
|
||||||
for ns := range namespaces {
|
for ns := range namespaces {
|
||||||
result = append(result, ns)
|
result = append(result, ns)
|
||||||
@@ -424,7 +417,7 @@ func Panic(args ...any) {
|
|||||||
Namespace: DefaultNamespace,
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) > 0 {
|
if len(args) >= 0 {
|
||||||
switch args[0].(type) {
|
switch args[0].(type) {
|
||||||
case error:
|
case error:
|
||||||
panic(args[0])
|
panic(args[0])
|
||||||
@@ -448,7 +441,7 @@ func Panicf(format string, args ...any) {
|
|||||||
Namespace: DefaultNamespace,
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) > 0 {
|
if len(args) >= 0 {
|
||||||
switch args[0].(type) {
|
switch args[0].(type) {
|
||||||
case error:
|
case error:
|
||||||
panic(args[0])
|
panic(args[0])
|
||||||
@@ -471,7 +464,7 @@ func Panicln(args ...any) {
|
|||||||
Namespace: DefaultNamespace,
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) > 0 {
|
if len(args) >= 0 {
|
||||||
switch args[0].(type) {
|
switch args[0].(type) {
|
||||||
case error:
|
case error:
|
||||||
panic(args[0])
|
panic(args[0])
|
||||||
@@ -556,37 +549,3 @@ func fileInfo(skip int) string {
|
|||||||
}
|
}
|
||||||
return fmt.Sprintf("%s:%d", file, line)
|
return fmt.Sprintf("%s:%d", file, line)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Broadcast sends an [Entry] to all registered clients. This is the public
|
|
||||||
// entry point used by adapter packages (such as the slog handler) that
|
|
||||||
// construct entries themselves. The unexported level field is inferred from
|
|
||||||
// [Entry.Level] when not already set.
|
|
||||||
func Broadcast(e Entry) {
|
|
||||||
if e.level == 0 && e.Level != "" && e.Level != "TRACE" {
|
|
||||||
e.level = parseLevelString(e.Level)
|
|
||||||
}
|
|
||||||
createLog(e)
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseLevelString(s string) Level {
|
|
||||||
switch s {
|
|
||||||
case "TRACE":
|
|
||||||
return LTrace
|
|
||||||
case "DEBUG":
|
|
||||||
return LDebug
|
|
||||||
case "INFO":
|
|
||||||
return LInfo
|
|
||||||
case "NOTICE":
|
|
||||||
return LNotice
|
|
||||||
case "WARN":
|
|
||||||
return LWarn
|
|
||||||
case "ERROR":
|
|
||||||
return LError
|
|
||||||
case "PANIC":
|
|
||||||
return LPanic
|
|
||||||
case "FATAL":
|
|
||||||
return LFatal
|
|
||||||
default:
|
|
||||||
return LInfo
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
508
log/log_test.go
508
log/log_test.go
@@ -4,21 +4,8 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// getEntry reads from a client with a timeout to avoid hanging tests.
|
|
||||||
func getEntry(c *Client, timeout time.Duration) (Entry, bool) {
|
|
||||||
ch := make(chan Entry, 1)
|
|
||||||
go func() { ch <- c.Get() }()
|
|
||||||
select {
|
|
||||||
case e := <-ch:
|
|
||||||
return e, true
|
|
||||||
case <-time.After(timeout):
|
|
||||||
return Entry{}, false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test CreateClient() and Client.Destroy()
|
// Test CreateClient() and Client.Destroy()
|
||||||
func TestCreateDestroy(t *testing.T) {
|
func TestCreateDestroy(t *testing.T) {
|
||||||
// Ensure only stderr exists at the beginning
|
// Ensure only stderr exists at the beginning
|
||||||
@@ -77,477 +64,70 @@ func TestOrder(t *testing.T) {
|
|||||||
t.Error("Trace input doesn't match output")
|
t.Error("Trace input doesn't match output")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Debug prints out logs on debug level
|
||||||
func TestDebug(t *testing.T) {
|
func TestDebug(t *testing.T) {
|
||||||
c := CreateClient(DefaultNamespace)
|
Debug("Test of Debug")
|
||||||
c.SetLogLevel(LDebug)
|
// if logLevel >= LDebug {
|
||||||
|
// entry := logger.WithFields(logrus.Fields{})
|
||||||
Debug("debug message")
|
// entry.Data["file"] = fileInfo(2)
|
||||||
e, ok := getEntry(c, time.Second)
|
// entry.Debug(args...)
|
||||||
if !ok {
|
// }
|
||||||
t.Fatal("timed out waiting for debug entry")
|
|
||||||
}
|
|
||||||
if e.Level != "DEBUG" {
|
|
||||||
t.Errorf("level = %q, want DEBUG", e.Level)
|
|
||||||
}
|
|
||||||
if e.Output != "debug message" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "debug message")
|
|
||||||
}
|
|
||||||
if e.Namespace != DefaultNamespace {
|
|
||||||
t.Errorf("namespace = %q, want %q", e.Namespace, DefaultNamespace)
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDebugf(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LDebug)
|
|
||||||
|
|
||||||
Debugf("hello %s %d", "world", 42)
|
|
||||||
e, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Output != "hello world 42" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "hello world 42")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Info prints out logs on info level
|
||||||
func TestInfo(t *testing.T) {
|
func TestInfo(t *testing.T) {
|
||||||
c := CreateClient(DefaultNamespace)
|
// if logLevel >= LInfo {
|
||||||
c.SetLogLevel(LInfo)
|
// entry := logger.WithFields(logrus.Fields{})
|
||||||
|
// entry.Data["file"] = fileInfo(2)
|
||||||
Info("info message")
|
// entry.Info(args...)
|
||||||
e, ok := getEntry(c, time.Second)
|
// }
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for info entry")
|
|
||||||
}
|
|
||||||
if e.Level != "INFO" {
|
|
||||||
t.Errorf("level = %q, want INFO", e.Level)
|
|
||||||
}
|
|
||||||
if e.Output != "info message" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "info message")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInfof(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LInfo)
|
|
||||||
|
|
||||||
Infof("count: %d", 99)
|
|
||||||
e, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Output != "count: 99" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "count: 99")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Print prints out logs on info level
|
||||||
func TestPrint(t *testing.T) {
|
func TestPrint(t *testing.T) {
|
||||||
c := CreateClient(DefaultNamespace)
|
// if logLevel >= LInfo {
|
||||||
c.SetLogLevel(LInfo)
|
// entry := logger.WithFields(logrus.Fields{})
|
||||||
|
// entry.Data["file"] = fileInfo(2)
|
||||||
Print("print message")
|
// entry.Info(args...)
|
||||||
e, ok := getEntry(c, time.Second)
|
// }
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
// Print is an alias for Info
|
|
||||||
if e.Level != "INFO" {
|
|
||||||
t.Errorf("level = %q, want INFO", e.Level)
|
|
||||||
}
|
|
||||||
if e.Output != "print message" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "print message")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPrintf(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LInfo)
|
|
||||||
|
|
||||||
Printf("formatted %s", "print")
|
|
||||||
e, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Output != "formatted print" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "formatted print")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNotice(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LNotice)
|
|
||||||
|
|
||||||
Notice("notice message")
|
|
||||||
e, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Level != "NOTICE" {
|
|
||||||
t.Errorf("level = %q, want NOTICE", e.Level)
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Warn prints out logs on warn level
|
||||||
func TestWarn(t *testing.T) {
|
func TestWarn(t *testing.T) {
|
||||||
c := CreateClient(DefaultNamespace)
|
// if logLevel >= LWarn {
|
||||||
c.SetLogLevel(LWarn)
|
// entry := logger.WithFields(logrus.Fields{})
|
||||||
|
// entry.Data["file"] = fileInfo(2)
|
||||||
Warn("warning message")
|
// entry.Warn(args...)
|
||||||
e, ok := getEntry(c, time.Second)
|
// }
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for warn entry")
|
|
||||||
}
|
|
||||||
if e.Level != "WARN" {
|
|
||||||
t.Errorf("level = %q, want WARN", e.Level)
|
|
||||||
}
|
|
||||||
if e.Output != "warning message" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "warning message")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestWarnf(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LWarn)
|
|
||||||
|
|
||||||
Warnf("warn %d", 1)
|
|
||||||
e, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Output != "warn 1" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "warn 1")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error prints out logs on error level
|
||||||
func TestError(t *testing.T) {
|
func TestError(t *testing.T) {
|
||||||
c := CreateClient(DefaultNamespace)
|
// if logLevel >= LError {
|
||||||
c.SetLogLevel(LError)
|
// entry := logger.WithFields(logrus.Fields{})
|
||||||
|
// entry.Data["file"] = fileInfo(2)
|
||||||
Error("error message")
|
// entry.Error(args...)
|
||||||
e, ok := getEntry(c, time.Second)
|
// }
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for error entry")
|
|
||||||
}
|
|
||||||
if e.Level != "ERROR" {
|
|
||||||
t.Errorf("level = %q, want ERROR", e.Level)
|
|
||||||
}
|
|
||||||
if e.Output != "error message" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "error message")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestErrorf(t *testing.T) {
|
// Fatal prints out logs on fatal level
|
||||||
c := CreateClient(DefaultNamespace)
|
func TestFatal(t *testing.T) {
|
||||||
c.SetLogLevel(LError)
|
// if logLevel >= LFatal {
|
||||||
|
// entry := logger.WithFields(logrus.Fields{})
|
||||||
Errorf("err: %s", "something broke")
|
// entry.Data["file"] = fileInfo(2)
|
||||||
e, ok := getEntry(c, time.Second)
|
// entry.Fatal(args...)
|
||||||
if !ok {
|
// }
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Output != "err: something broke" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "err: something broke")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Panic prints out logs on panic level
|
||||||
func TestPanic(t *testing.T) {
|
func TestPanic(t *testing.T) {
|
||||||
c := CreateClient(DefaultNamespace)
|
// if logLevel >= LPanic {
|
||||||
c.SetLogLevel(LPanic)
|
// entry := logger.WithFields(logrus.Fields{})
|
||||||
|
// entry.Data["file"] = fileInfo(2)
|
||||||
defer func() {
|
// entry.Panic(args...)
|
||||||
r := recover()
|
// }
|
||||||
if r == nil {
|
|
||||||
t.Error("expected panic, got nil")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}()
|
|
||||||
|
|
||||||
Panic("panic message")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPanicf(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LPanic)
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
r := recover()
|
|
||||||
if r == nil {
|
|
||||||
t.Error("expected panic, got nil")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}()
|
|
||||||
|
|
||||||
Panicf("panic %d", 42)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPanicln(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LPanic)
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
r := recover()
|
|
||||||
if r == nil {
|
|
||||||
t.Error("expected panic, got nil")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}()
|
|
||||||
|
|
||||||
Panicln("panic line")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLogLevelFiltering verifies that the client's log level is stored correctly.
|
|
||||||
// Note: level filtering only applies to stderr output, not to client channels.
|
|
||||||
// All entries matching the namespace are delivered to the client channel regardless of level.
|
|
||||||
func TestLogLevelFiltering(t *testing.T) {
|
|
||||||
c := CreateClient(DefaultNamespace)
|
|
||||||
c.SetLogLevel(LWarn)
|
|
||||||
|
|
||||||
if c.GetLogLevel() != LWarn {
|
|
||||||
t.Errorf("expected log level LWarn, got %d", c.GetLogLevel())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Both entries arrive at the client channel (level filtering is stderr-only)
|
|
||||||
Info("info message")
|
|
||||||
Warn("warn message")
|
|
||||||
|
|
||||||
e1, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for first entry")
|
|
||||||
}
|
|
||||||
if e1.Output != "info message" {
|
|
||||||
t.Errorf("expected 'info message', got %q", e1.Output)
|
|
||||||
}
|
|
||||||
|
|
||||||
e2, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for second entry")
|
|
||||||
}
|
|
||||||
if e2.Output != "warn message" {
|
|
||||||
t.Errorf("expected 'warn message', got %q", e2.Output)
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestNamespaceFiltering verifies clients only receive matching namespaces.
|
|
||||||
func TestNamespaceFiltering(t *testing.T) {
|
|
||||||
c := CreateClient("api")
|
|
||||||
c.SetLogLevel(LTrace)
|
|
||||||
|
|
||||||
apiLogger := NewLogger("api")
|
|
||||||
dbLogger := NewLogger("database")
|
|
||||||
|
|
||||||
// Log to database namespace — should not arrive at "api" client
|
|
||||||
dbLogger.Info("db message")
|
|
||||||
|
|
||||||
// Log to api namespace — should arrive
|
|
||||||
apiLogger.Info("api message")
|
|
||||||
|
|
||||||
e, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for api entry")
|
|
||||||
}
|
|
||||||
if e.Output != "api message" {
|
|
||||||
t.Errorf("expected 'api message', got %q", e.Output)
|
|
||||||
}
|
|
||||||
if e.Namespace != "api" {
|
|
||||||
t.Errorf("namespace = %q, want 'api'", e.Namespace)
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestMultiNamespaceClient verifies a client subscribed to multiple namespaces.
|
|
||||||
func TestMultiNamespaceClient(t *testing.T) {
|
|
||||||
c := CreateClient("api", "auth")
|
|
||||||
c.SetLogLevel(LTrace)
|
|
||||||
|
|
||||||
apiLogger := NewLogger("api")
|
|
||||||
authLogger := NewLogger("auth")
|
|
||||||
dbLogger := NewLogger("database")
|
|
||||||
|
|
||||||
dbLogger.Info("db message") // filtered out
|
|
||||||
apiLogger.Info("api message") // should arrive
|
|
||||||
authLogger.Info("auth message") // should arrive
|
|
||||||
|
|
||||||
e1, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for first entry")
|
|
||||||
}
|
|
||||||
if e1.Output != "api message" {
|
|
||||||
t.Errorf("first entry = %q, want 'api message'", e1.Output)
|
|
||||||
}
|
|
||||||
|
|
||||||
e2, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for second entry")
|
|
||||||
}
|
|
||||||
if e2.Output != "auth message" {
|
|
||||||
t.Errorf("second entry = %q, want 'auth message'", e2.Output)
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestGetNamespaces verifies the namespace registry.
|
|
||||||
func TestGetNamespaces(t *testing.T) {
|
|
||||||
l := NewLogger("test-ns-registry")
|
|
||||||
l.Info("register this namespace")
|
|
||||||
|
|
||||||
nss := GetNamespaces()
|
|
||||||
found := false
|
|
||||||
for _, ns := range nss {
|
|
||||||
if ns == "test-ns-registry" {
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
t.Errorf("expected 'test-ns-registry' in GetNamespaces(), got %v", nss)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLoggerDebugln verifies the Debugln method on Logger.
|
|
||||||
func TestLoggerDebugln(t *testing.T) {
|
|
||||||
c := CreateClient("debugln-test")
|
|
||||||
c.SetLogLevel(LDebug)
|
|
||||||
|
|
||||||
l := NewLogger("debugln-test")
|
|
||||||
l.Debugln("debugln message")
|
|
||||||
|
|
||||||
e, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Level != "DEBUG" {
|
|
||||||
t.Errorf("level = %q, want DEBUG", e.Level)
|
|
||||||
}
|
|
||||||
// Sprintln appends a newline
|
|
||||||
if e.Output != "debugln message\n" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "debugln message\n")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestNewLoggerEmptyNamespace verifies empty namespace defaults to DefaultNamespace.
|
|
||||||
func TestNewLoggerEmptyNamespace(t *testing.T) {
|
|
||||||
l := NewLogger("")
|
|
||||||
if l.Namespace != DefaultNamespace {
|
|
||||||
t.Errorf("namespace = %q, want %q", l.Namespace, DefaultNamespace)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestFileInfo verifies fileInfo returns a non-empty file:line string.
|
|
||||||
func TestFileInfo(t *testing.T) {
|
|
||||||
fi := fileInfo(1)
|
|
||||||
if fi == "" || fi == "<???>:1" {
|
|
||||||
t.Errorf("fileInfo returned unexpected value: %q", fi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestColorize verifies color wrapping.
|
|
||||||
func TestColorize(t *testing.T) {
|
|
||||||
SetColorEnabled(true)
|
|
||||||
result := colorize("hello", colorRed)
|
|
||||||
expected := colorRed + "hello" + colorReset
|
|
||||||
if result != expected {
|
|
||||||
t.Errorf("colorize with color enabled: got %q, want %q", result, expected)
|
|
||||||
}
|
|
||||||
|
|
||||||
SetColorEnabled(false)
|
|
||||||
result = colorize("hello", colorRed)
|
|
||||||
if result != "hello" {
|
|
||||||
t.Errorf("colorize with color disabled: got %q, want %q", result, "hello")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Restore default
|
|
||||||
SetColorEnabled(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestParseLevelString verifies level string parsing.
|
|
||||||
func TestParseLevelString(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
input string
|
|
||||||
want Level
|
|
||||||
}{
|
|
||||||
{"TRACE", LTrace},
|
|
||||||
{"DEBUG", LDebug},
|
|
||||||
{"INFO", LInfo},
|
|
||||||
{"NOTICE", LNotice},
|
|
||||||
{"WARN", LWarn},
|
|
||||||
{"ERROR", LError},
|
|
||||||
{"PANIC", LPanic},
|
|
||||||
{"FATAL", LFatal},
|
|
||||||
{"UNKNOWN", LInfo}, // default
|
|
||||||
{"", LInfo}, // default
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
got := parseLevelString(tt.input)
|
|
||||||
if got != tt.want {
|
|
||||||
t.Errorf("parseLevelString(%q) = %d, want %d", tt.input, got, tt.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestBroadcast verifies the public Broadcast function.
|
|
||||||
func TestBroadcast(t *testing.T) {
|
|
||||||
c := CreateClient("broadcast-ns")
|
|
||||||
c.SetLogLevel(LTrace)
|
|
||||||
|
|
||||||
e := Entry{
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Output: "broadcast test",
|
|
||||||
File: "test.go:1",
|
|
||||||
Level: "WARN",
|
|
||||||
Namespace: "broadcast-ns",
|
|
||||||
}
|
|
||||||
Broadcast(e)
|
|
||||||
|
|
||||||
got, ok := getEntry(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if got.Output != "broadcast test" {
|
|
||||||
t.Errorf("output = %q, want %q", got.Output, "broadcast test")
|
|
||||||
}
|
|
||||||
if got.Level != "WARN" {
|
|
||||||
t.Errorf("level = %q, want WARN", got.Level)
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestMatchesNamespace verifies the namespace matching helper.
|
|
||||||
func TestMatchesNamespace(t *testing.T) {
|
|
||||||
// Client with no namespace filter matches everything
|
|
||||||
c := CreateClient()
|
|
||||||
if !c.matchesNamespace("anything") {
|
|
||||||
t.Error("empty Namespaces should match all")
|
|
||||||
}
|
|
||||||
c.Destroy()
|
|
||||||
|
|
||||||
// Client with specific namespaces
|
|
||||||
c2 := CreateClient("api", "auth")
|
|
||||||
if !c2.matchesNamespace("api") {
|
|
||||||
t.Error("should match 'api'")
|
|
||||||
}
|
|
||||||
if !c2.matchesNamespace("auth") {
|
|
||||||
t.Error("should match 'auth'")
|
|
||||||
}
|
|
||||||
if c2.matchesNamespace("database") {
|
|
||||||
t.Error("should not match 'database'")
|
|
||||||
}
|
|
||||||
c2.Destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFlush(t *testing.T) {
|
func TestFlush(t *testing.T) {
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ func (l Logger) Trace(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -42,7 +42,7 @@ func (l Logger) Tracef(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -56,7 +56,7 @@ func (l Logger) Traceln(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -70,7 +70,7 @@ func (l Logger) Debug(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "DEBUG",
|
Level: "DEBUG",
|
||||||
level: LDebug,
|
level: LDebug,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -84,21 +84,7 @@ func (l Logger) Debugf(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "DEBUG",
|
|
||||||
level: LDebug,
|
|
||||||
Namespace: l.Namespace,
|
|
||||||
}
|
|
||||||
createLog(e)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Debugln prints out logs on debug level with a newline
|
|
||||||
func (l Logger) Debugln(args ...any) {
|
|
||||||
output := fmt.Sprintln(args...)
|
|
||||||
e := Entry{
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Output: output,
|
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
|
||||||
Level: "DEBUG",
|
Level: "DEBUG",
|
||||||
level: LDebug,
|
level: LDebug,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -112,7 +98,7 @@ func (l Logger) Info(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -126,7 +112,7 @@ func (l Logger) Infof(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -140,7 +126,7 @@ func (l Logger) Infoln(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -154,7 +140,7 @@ func (l Logger) Notice(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -168,7 +154,7 @@ func (l Logger) Noticef(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -182,7 +168,7 @@ func (l Logger) Noticeln(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -196,7 +182,7 @@ func (l Logger) Warn(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -210,7 +196,7 @@ func (l Logger) Warnf(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -224,7 +210,7 @@ func (l Logger) Warnln(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -238,7 +224,7 @@ func (l Logger) Error(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -252,7 +238,7 @@ func (l Logger) Errorf(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -266,7 +252,7 @@ func (l Logger) Errorln(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -280,13 +266,13 @@ func (l Logger) Panic(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) > 0 {
|
if len(args) >= 0 {
|
||||||
switch args[0].(type) {
|
switch args[0].(type) {
|
||||||
case error:
|
case error:
|
||||||
panic(args[0])
|
panic(args[0])
|
||||||
@@ -304,13 +290,13 @@ func (l Logger) Panicf(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) > 0 {
|
if len(args) >= 0 {
|
||||||
switch args[0].(type) {
|
switch args[0].(type) {
|
||||||
case error:
|
case error:
|
||||||
panic(args[0])
|
panic(args[0])
|
||||||
@@ -328,13 +314,13 @@ func (l Logger) Panicln(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) > 0 {
|
if len(args) >= 0 {
|
||||||
switch args[0].(type) {
|
switch args[0].(type) {
|
||||||
case error:
|
case error:
|
||||||
panic(args[0])
|
panic(args[0])
|
||||||
@@ -352,7 +338,7 @@ func (l Logger) Fatal(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -368,7 +354,7 @@ func (l Logger) Fatalf(format string, args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
@@ -384,7 +370,7 @@ func (l Logger) Fatalln(args ...any) {
|
|||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2 + l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
Namespace: l.Namespace,
|
Namespace: l.Namespace,
|
||||||
|
|||||||
165
slog/handler.go
165
slog/handler.go
@@ -1,165 +0,0 @@
|
|||||||
// Package slog provides a [log/slog.Handler] that routes structured log
|
|
||||||
// records into the log-socket broadcasting system, giving every slog-based
|
|
||||||
// caller free WebSocket streaming and the browser viewer UI.
|
|
||||||
package slog
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/taigrr/log-socket/v2/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler implements [slog.Handler] by converting each [slog.Record] into a
|
|
||||||
// log-socket [log.Entry] and feeding it through the normal broadcast path.
|
|
||||||
//
|
|
||||||
// Attributes accumulated via [Handler.WithAttrs] are prepended to the log
|
|
||||||
// message as key=value pairs. Groups set via [Handler.WithGroup] prefix
|
|
||||||
// attribute keys with "group.".
|
|
||||||
type Handler struct {
|
|
||||||
namespace string
|
|
||||||
level slog.Level
|
|
||||||
attrs []slog.Attr
|
|
||||||
groups []string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ensure interface compliance at compile time.
|
|
||||||
var _ slog.Handler = (*Handler)(nil)
|
|
||||||
|
|
||||||
// Option configures a [Handler].
|
|
||||||
type Option func(*Handler)
|
|
||||||
|
|
||||||
// WithNamespace sets the log-socket namespace for entries produced by this
|
|
||||||
// handler. If empty, [log.DefaultNamespace] is used.
|
|
||||||
func WithNamespace(ns string) Option {
|
|
||||||
return func(h *Handler) {
|
|
||||||
h.namespace = ns
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithLevel sets the minimum slog level the handler will accept.
|
|
||||||
func WithLevel(l slog.Level) Option {
|
|
||||||
return func(h *Handler) {
|
|
||||||
h.level = l
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewHandler returns a new [Handler] that writes to the log-socket broadcast
|
|
||||||
// system. Options may be used to set the namespace and minimum level.
|
|
||||||
func NewHandler(opts ...Option) *Handler {
|
|
||||||
h := &Handler{
|
|
||||||
namespace: log.DefaultNamespace,
|
|
||||||
level: slog.LevelDebug,
|
|
||||||
}
|
|
||||||
for _, o := range opts {
|
|
||||||
o(h)
|
|
||||||
}
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enabled reports whether the handler is configured to process records at
|
|
||||||
// the given level.
|
|
||||||
func (h *Handler) Enabled(_ context.Context, level slog.Level) bool {
|
|
||||||
return level >= h.level
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle converts r into a log-socket Entry and broadcasts it.
|
|
||||||
func (h *Handler) Handle(_ context.Context, r slog.Record) error {
|
|
||||||
var b strings.Builder
|
|
||||||
b.WriteString(r.Message)
|
|
||||||
|
|
||||||
// Append pre-collected attrs.
|
|
||||||
for _, a := range h.attrs {
|
|
||||||
writeAttr(&b, h.groups, a)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Append record-level attrs.
|
|
||||||
r.Attrs(func(a slog.Attr) bool {
|
|
||||||
writeAttr(&b, h.groups, a)
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
|
|
||||||
file := "???"
|
|
||||||
if r.PC != 0 {
|
|
||||||
fs := runtime.CallersFrames([]uintptr{r.PC})
|
|
||||||
f, _ := fs.Next()
|
|
||||||
if f.File != "" {
|
|
||||||
short := f.File
|
|
||||||
if idx := strings.LastIndex(short, "/"); idx >= 0 {
|
|
||||||
short = short[idx+1:]
|
|
||||||
}
|
|
||||||
file = fmt.Sprintf("%s:%d", short, f.Line)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
e := log.Entry{
|
|
||||||
Timestamp: r.Time,
|
|
||||||
Output: b.String(),
|
|
||||||
File: file,
|
|
||||||
Level: slogLevelToString(r.Level),
|
|
||||||
Namespace: h.namespace,
|
|
||||||
}
|
|
||||||
log.Broadcast(e)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithAttrs returns a new Handler with the given attributes appended.
|
|
||||||
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
||||||
h2 := h.clone()
|
|
||||||
h2.attrs = append(h2.attrs, attrs...)
|
|
||||||
return h2
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithGroup returns a new Handler where subsequent attributes are nested
|
|
||||||
// under the given group name.
|
|
||||||
func (h *Handler) WithGroup(name string) slog.Handler {
|
|
||||||
if name == "" {
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
h2 := h.clone()
|
|
||||||
h2.groups = append(h2.groups, name)
|
|
||||||
return h2
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) clone() *Handler {
|
|
||||||
h2 := &Handler{
|
|
||||||
namespace: h.namespace,
|
|
||||||
level: h.level,
|
|
||||||
attrs: make([]slog.Attr, len(h.attrs)),
|
|
||||||
groups: make([]string, len(h.groups)),
|
|
||||||
}
|
|
||||||
copy(h2.attrs, h.attrs)
|
|
||||||
copy(h2.groups, h.groups)
|
|
||||||
return h2
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeAttr(b *strings.Builder, groups []string, a slog.Attr) {
|
|
||||||
a.Value = a.Value.Resolve()
|
|
||||||
if a.Equal(slog.Attr{}) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
b.WriteByte(' ')
|
|
||||||
for _, g := range groups {
|
|
||||||
b.WriteString(g)
|
|
||||||
b.WriteByte('.')
|
|
||||||
}
|
|
||||||
b.WriteString(a.Key)
|
|
||||||
b.WriteByte('=')
|
|
||||||
b.WriteString(a.Value.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
func slogLevelToString(l slog.Level) string {
|
|
||||||
switch {
|
|
||||||
case l >= slog.LevelError:
|
|
||||||
return "ERROR"
|
|
||||||
case l >= slog.LevelWarn:
|
|
||||||
return "WARN"
|
|
||||||
case l >= slog.LevelInfo:
|
|
||||||
return "INFO"
|
|
||||||
default:
|
|
||||||
return "DEBUG"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
package slog
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log/slog"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/taigrr/log-socket/v2/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
// getWithTimeout reads from a log client with a timeout to avoid hanging tests.
|
|
||||||
func getWithTimeout(c *log.Client, timeout time.Duration) (log.Entry, bool) {
|
|
||||||
ch := make(chan log.Entry, 1)
|
|
||||||
go func() { ch <- c.Get() }()
|
|
||||||
select {
|
|
||||||
case e := <-ch:
|
|
||||||
return e, true
|
|
||||||
case <-time.After(timeout):
|
|
||||||
return log.Entry{}, false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandler_Enabled(t *testing.T) {
|
|
||||||
h := NewHandler(WithLevel(slog.LevelWarn))
|
|
||||||
if h.Enabled(context.Background(), slog.LevelInfo) {
|
|
||||||
t.Error("expected Info to be disabled when min level is Warn")
|
|
||||||
}
|
|
||||||
if !h.Enabled(context.Background(), slog.LevelWarn) {
|
|
||||||
t.Error("expected Warn to be enabled")
|
|
||||||
}
|
|
||||||
if !h.Enabled(context.Background(), slog.LevelError) {
|
|
||||||
t.Error("expected Error to be enabled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandler_Handle(t *testing.T) {
|
|
||||||
c := log.CreateClient()
|
|
||||||
defer c.Destroy()
|
|
||||||
c.SetLogLevel(log.LTrace)
|
|
||||||
|
|
||||||
h := NewHandler(WithNamespace("test-ns"))
|
|
||||||
logger := slog.New(h)
|
|
||||||
|
|
||||||
logger.Info("hello world", "key", "value")
|
|
||||||
|
|
||||||
e, ok := getWithTimeout(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out waiting for log entry")
|
|
||||||
}
|
|
||||||
if e.Namespace != "test-ns" {
|
|
||||||
t.Errorf("namespace = %q, want %q", e.Namespace, "test-ns")
|
|
||||||
}
|
|
||||||
if e.Level != "INFO" {
|
|
||||||
t.Errorf("level = %q, want INFO", e.Level)
|
|
||||||
}
|
|
||||||
if e.Output == "" {
|
|
||||||
t.Error("output should not be empty")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandler_WithAttrs(t *testing.T) {
|
|
||||||
c := log.CreateClient()
|
|
||||||
defer c.Destroy()
|
|
||||||
c.SetLogLevel(log.LTrace)
|
|
||||||
|
|
||||||
h := NewHandler()
|
|
||||||
h2 := h.WithAttrs([]slog.Attr{slog.String("service", "api")})
|
|
||||||
logger := slog.New(h2)
|
|
||||||
|
|
||||||
logger.Info("request")
|
|
||||||
|
|
||||||
e, ok := getWithTimeout(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Output != "request service=api" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "request service=api")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandler_WithGroup(t *testing.T) {
|
|
||||||
c := log.CreateClient()
|
|
||||||
defer c.Destroy()
|
|
||||||
c.SetLogLevel(log.LTrace)
|
|
||||||
|
|
||||||
h := NewHandler()
|
|
||||||
h2 := h.WithGroup("http").WithAttrs([]slog.Attr{slog.Int("status", 200)})
|
|
||||||
logger := slog.New(h2)
|
|
||||||
|
|
||||||
logger.Info("done")
|
|
||||||
|
|
||||||
e, ok := getWithTimeout(c, time.Second)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("timed out")
|
|
||||||
}
|
|
||||||
if e.Output != "done http.status=200" {
|
|
||||||
t.Errorf("output = %q, want %q", e.Output, "done http.status=200")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSlogLevelMapping(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
level slog.Level
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{slog.LevelDebug, "DEBUG"},
|
|
||||||
{slog.LevelInfo, "INFO"},
|
|
||||||
{slog.LevelWarn, "WARN"},
|
|
||||||
{slog.LevelError, "ERROR"},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
got := slogLevelToString(tt.level)
|
|
||||||
if got != tt.want {
|
|
||||||
t.Errorf("slogLevelToString(%v) = %q, want %q", tt.level, got, tt.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package ws
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
logger "github.com/taigrr/log-socket/v2/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNamespacesHandler(t *testing.T) {
|
|
||||||
// Log to a known namespace to ensure it appears
|
|
||||||
nsLogger := logger.NewLogger("ns-handler-test")
|
|
||||||
nsLogger.Info("register namespace")
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/api/namespaces", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
NamespacesHandler(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
ct := w.Header().Get("Content-Type")
|
|
||||||
if ct != "application/json" {
|
|
||||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
|
||||||
}
|
|
||||||
|
|
||||||
var result struct {
|
|
||||||
Namespaces []string `json:"namespaces"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
|
||||||
t.Fatalf("failed to unmarshal response: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
found := false
|
|
||||||
for _, ns := range result.Namespaces {
|
|
||||||
if ns == "ns-handler-test" {
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
t.Errorf("namespace 'ns-handler-test' not found in %v", result.Namespaces)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNamespacesHandler_ResponseFormat(t *testing.T) {
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/api/namespaces", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
NamespacesHandler(w, req)
|
|
||||||
|
|
||||||
var result map[string]interface{}
|
|
||||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
|
||||||
t.Fatalf("response is not valid JSON: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := result["namespaces"]; !ok {
|
|
||||||
t.Error("response missing 'namespaces' key")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,7 +23,7 @@ func LogSocketHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
if namespacesParam != "" {
|
if namespacesParam != "" {
|
||||||
namespaces = strings.Split(namespacesParam, ",")
|
namespaces = strings.Split(namespacesParam, ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := upgrader.Upgrade(w, r, nil)
|
c, err := upgrader.Upgrade(w, r, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("upgrade:", err)
|
logger.Error("upgrade:", err)
|
||||||
|
|||||||
@@ -1,127 +0,0 @@
|
|||||||
package ws
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
logger "github.com/taigrr/log-socket/v2/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestSetUpgrader(t *testing.T) {
|
|
||||||
custom := websocket.Upgrader{
|
|
||||||
ReadBufferSize: 2048,
|
|
||||||
WriteBufferSize: 2048,
|
|
||||||
}
|
|
||||||
SetUpgrader(custom)
|
|
||||||
if upgrader.ReadBufferSize != 2048 {
|
|
||||||
t.Errorf("ReadBufferSize = %d, want 2048", upgrader.ReadBufferSize)
|
|
||||||
}
|
|
||||||
if upgrader.WriteBufferSize != 2048 {
|
|
||||||
t.Errorf("WriteBufferSize = %d, want 2048", upgrader.WriteBufferSize)
|
|
||||||
}
|
|
||||||
// Reset to default
|
|
||||||
SetUpgrader(websocket.Upgrader{})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLogSocketHandler_NonWebSocket(t *testing.T) {
|
|
||||||
// A non-upgrade request should fail gracefully (upgrader returns error)
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/ws", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
LogSocketHandler(w, req)
|
|
||||||
// The upgrader should return a 400-level error for non-websocket requests
|
|
||||||
if w.Code == http.StatusOK || w.Code == http.StatusSwitchingProtocols {
|
|
||||||
t.Errorf("expected error status for non-websocket request, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLogSocketHandler_WebSocket(t *testing.T) {
|
|
||||||
// Set upgrader with permissive origin check for testing
|
|
||||||
SetUpgrader(websocket.Upgrader{
|
|
||||||
CheckOrigin: func(r *http.Request) bool { return true },
|
|
||||||
})
|
|
||||||
defer SetUpgrader(websocket.Upgrader{})
|
|
||||||
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(LogSocketHandler))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws"
|
|
||||||
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to connect: %v", err)
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
// Send a log entry and verify it arrives over the websocket
|
|
||||||
testLogger := logger.NewLogger("ws-test")
|
|
||||||
testLogger.Info("test message for websocket")
|
|
||||||
|
|
||||||
// Read messages until we find our test entry (the handler itself
|
|
||||||
// logs "Websocket client attached." which may arrive first)
|
|
||||||
conn.SetReadDeadline(time.Now().Add(2 * time.Second))
|
|
||||||
var found bool
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
_, message, err := conn.ReadMessage()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to read message: %v", err)
|
|
||||||
}
|
|
||||||
var entry logger.Entry
|
|
||||||
if err := json.Unmarshal(message, &entry); err != nil {
|
|
||||||
t.Fatalf("failed to unmarshal entry: %v", err)
|
|
||||||
}
|
|
||||||
if entry.Namespace == "ws-test" && entry.Level == "INFO" {
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
t.Error("did not receive expected log entry with namespace ws-test")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLogSocketHandler_NamespaceFilter(t *testing.T) {
|
|
||||||
SetUpgrader(websocket.Upgrader{
|
|
||||||
CheckOrigin: func(r *http.Request) bool { return true },
|
|
||||||
})
|
|
||||||
defer SetUpgrader(websocket.Upgrader{})
|
|
||||||
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(LogSocketHandler))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
// Connect with namespace filter
|
|
||||||
wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws?namespaces=filtered-ns"
|
|
||||||
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to connect: %v", err)
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
// Send a log to a different namespace — it should NOT be received
|
|
||||||
otherLogger := logger.NewLogger("other-ns")
|
|
||||||
otherLogger.Info("should not arrive")
|
|
||||||
|
|
||||||
// Send a log to the filtered namespace — it SHOULD be received
|
|
||||||
filteredLogger := logger.NewLogger("filtered-ns")
|
|
||||||
filteredLogger.Info("should arrive")
|
|
||||||
|
|
||||||
conn.SetReadDeadline(time.Now().Add(2 * time.Second))
|
|
||||||
_, message, err := conn.ReadMessage()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to read message: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var entry logger.Entry
|
|
||||||
if err := json.Unmarshal(message, &entry); err != nil {
|
|
||||||
t.Fatalf("failed to unmarshal entry: %v", err)
|
|
||||||
}
|
|
||||||
if entry.Namespace != "filtered-ns" {
|
|
||||||
t.Errorf("namespace = %q, want filtered-ns", entry.Namespace)
|
|
||||||
}
|
|
||||||
if !strings.Contains(entry.Output, "should arrive") {
|
|
||||||
t.Errorf("output = %q, want to contain 'should arrive'", entry.Output)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user