mirror of
https://github.com/taigrr/log-socket
synced 2026-03-20 16:02:28 -07:00
Compare commits
14 Commits
v1.0.0
...
cd/6-add-b
| Author | SHA1 | Date | |
|---|---|---|---|
| 085aadaaef | |||
| 93dd230be0 | |||
| f86c2dbf46 | |||
|
|
9c571ca955
|
||
|
|
45ba154d1e | ||
|
c89dda8333
|
|||
|
41aad10e6c
|
|||
| 64ab2564c1 | |||
| 1c00bc90b8 | |||
|
f114098a8c
|
|||
|
|
2571dbe347 | ||
|
80b80758de
|
|||
|
0fa4de7961
|
|||
|
50c507c8f4
|
23
.github/workflows/ci.yaml
vendored
Normal file
23
.github/workflows/ci.yaml
vendored
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
name: Go package
|
||||||
|
|
||||||
|
on: [push]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
go-version: "1.25"
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: go get .
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: go build -v ./...
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: go test -v ./...
|
||||||
501
CRUSH.md
Normal file
501
CRUSH.md
Normal file
@@ -0,0 +1,501 @@
|
|||||||
|
# CRUSH.md - Log Socket v2 Development Guide
|
||||||
|
|
||||||
|
This document provides context and conventions for working on **log-socket v2** - a real-time log viewer with WebSocket support and namespace filtering, written in Go.
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
Log Socket v2 is a Go library and standalone application that provides:
|
||||||
|
- Real-time log streaming via WebSocket
|
||||||
|
- **Namespace-based log organization** (NEW in v2)
|
||||||
|
- Web-based log viewer with namespace filtering
|
||||||
|
- Support for multiple log levels (TRACE, DEBUG, INFO, NOTICE, WARN, ERROR, PANIC, FATAL)
|
||||||
|
- Client architecture allowing multiple subscribers to filtered log streams
|
||||||
|
|
||||||
|
**Key insight**: This is both a library (importable Go package) and a standalone application. The main.go serves as an example implementation.
|
||||||
|
|
||||||
|
## Essential Commands
|
||||||
|
|
||||||
|
### Build
|
||||||
|
```bash
|
||||||
|
go build -v ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run Server
|
||||||
|
```bash
|
||||||
|
# Default (runs on 0.0.0.0:8080)
|
||||||
|
go run main.go
|
||||||
|
|
||||||
|
# Custom address
|
||||||
|
go run main.go -addr localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
Once running, open browser to `http://localhost:8080` to view logs.
|
||||||
|
|
||||||
|
### Test
|
||||||
|
```bash
|
||||||
|
go test -v ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Install
|
||||||
|
```bash
|
||||||
|
go install github.com/taigrr/log-socket/v2@latest
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dependencies
|
||||||
|
```bash
|
||||||
|
go get .
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
.
|
||||||
|
├── main.go # Example server with multiple namespaces
|
||||||
|
├── log/ # Core logging package
|
||||||
|
│ ├── log.go # Package-level logging functions + namespace tracking
|
||||||
|
│ ├── logger.go # Logger type with namespace support
|
||||||
|
│ ├── types.go # Type definitions (includes Namespace fields)
|
||||||
|
│ └── log_test.go # Tests
|
||||||
|
├── ws/ # WebSocket server
|
||||||
|
│ ├── server.go # LogSocketHandler with namespace filtering
|
||||||
|
│ └── namespaces.go # HTTP handler for namespace list API
|
||||||
|
└── browser/ # Web UI
|
||||||
|
├── browser.go # HTTP handler serving embedded HTML
|
||||||
|
└── viewer.html # Embedded web interface with namespace filter
|
||||||
|
```
|
||||||
|
|
||||||
|
## Major Changes in v2
|
||||||
|
|
||||||
|
### Module Path
|
||||||
|
- **v1**: `github.com/taigrr/log-socket`
|
||||||
|
- **v2**: `github.com/taigrr/log-socket/v2`
|
||||||
|
|
||||||
|
### Namespace Support
|
||||||
|
|
||||||
|
**Core concept**: Namespaces allow organizing logs by component, service, or domain (e.g., "api", "database", "auth").
|
||||||
|
|
||||||
|
#### Types Changes
|
||||||
|
|
||||||
|
**Entry** now includes:
|
||||||
|
```go
|
||||||
|
type Entry struct {
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
Output string `json:"output"`
|
||||||
|
File string `json:"file"`
|
||||||
|
Level string `json:"level"`
|
||||||
|
Namespace string `json:"namespace"` // NEW
|
||||||
|
level Level
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Client** now uses a slice for filtering:
|
||||||
|
```go
|
||||||
|
type Client struct {
|
||||||
|
LogLevel Level `json:"level"`
|
||||||
|
Namespaces []string `json:"namespaces"` // Empty = all namespaces
|
||||||
|
writer LogWriter
|
||||||
|
initialized bool
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Logger** has namespace field:
|
||||||
|
```go
|
||||||
|
type Logger struct {
|
||||||
|
FileInfoDepth int
|
||||||
|
Namespace string // NEW
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### API Changes
|
||||||
|
|
||||||
|
**CreateClient** now variadic:
|
||||||
|
```go
|
||||||
|
// v1
|
||||||
|
func CreateClient() *Client
|
||||||
|
|
||||||
|
// v2
|
||||||
|
func CreateClient(namespaces ...string) *Client
|
||||||
|
|
||||||
|
// Examples:
|
||||||
|
client := log.CreateClient() // All namespaces
|
||||||
|
client := log.CreateClient("api") // Single namespace
|
||||||
|
client := log.CreateClient("api", "database") // Multiple namespaces
|
||||||
|
```
|
||||||
|
|
||||||
|
**NewLogger** constructor added:
|
||||||
|
```go
|
||||||
|
func NewLogger(namespace string) *Logger
|
||||||
|
|
||||||
|
// Example:
|
||||||
|
apiLogger := log.NewLogger("api")
|
||||||
|
apiLogger.Info("API request received")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Namespace Tracking
|
||||||
|
|
||||||
|
Global namespace registry tracks all used namespaces:
|
||||||
|
```go
|
||||||
|
var (
|
||||||
|
namespaces map[string]bool
|
||||||
|
namespacesMux sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetNamespaces() []string
|
||||||
|
```
|
||||||
|
|
||||||
|
Namespaces are automatically registered when logs are created.
|
||||||
|
|
||||||
|
### WebSocket Changes
|
||||||
|
|
||||||
|
**Query parameter for filtering**:
|
||||||
|
```
|
||||||
|
ws://localhost:8080/ws?namespaces=api,database
|
||||||
|
```
|
||||||
|
|
||||||
|
The handler parses comma-separated namespace list and creates a filtered client.
|
||||||
|
|
||||||
|
### Web UI Changes
|
||||||
|
|
||||||
|
- Namespace filter input field added to controls
|
||||||
|
- Namespace column added to log table
|
||||||
|
- Reconnect button to apply namespace filter
|
||||||
|
- WebSocket URL includes namespace query parameter
|
||||||
|
|
||||||
|
## Code Organization & Architecture
|
||||||
|
|
||||||
|
### Log Package (`log/`)
|
||||||
|
|
||||||
|
Dual API remains, but with namespace support:
|
||||||
|
|
||||||
|
1. **Package-level functions**: Use "default" namespace
|
||||||
|
- `log.Info()`, `log.Debug()`, etc.
|
||||||
|
- All entry creations include `Namespace: DefaultNamespace`
|
||||||
|
|
||||||
|
2. **Logger instances**: Use custom namespace
|
||||||
|
- Create with `log.NewLogger(namespace)`
|
||||||
|
- All entry creations include `Namespace: l.Namespace`
|
||||||
|
|
||||||
|
### Client Architecture (Updated)
|
||||||
|
|
||||||
|
**Client filtering by namespace**:
|
||||||
|
|
||||||
|
1. **Empty Namespaces slice**: Receives all logs regardless of namespace
|
||||||
|
2. **Non-empty Namespaces**: Only receives logs matching one of the specified namespaces
|
||||||
|
|
||||||
|
**matchesNamespace helper**:
|
||||||
|
```go
|
||||||
|
func (c *Client) matchesNamespace(namespace string) bool {
|
||||||
|
// Empty Namespaces slice means match all
|
||||||
|
if len(c.Namespaces) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, ns := range c.Namespaces {
|
||||||
|
if ns == namespace {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Entry flow with namespace filtering**:
|
||||||
|
1. Log function called with namespace
|
||||||
|
2. `Entry` created with namespace field
|
||||||
|
3. Namespace registered in global map
|
||||||
|
4. `createLog()` sends to all clients
|
||||||
|
5. Each client checks `matchesNamespace()`
|
||||||
|
6. Only matching clients receive the entry
|
||||||
|
|
||||||
|
### WebSocket Handler (`ws/`)
|
||||||
|
|
||||||
|
**Namespace parameter parsing**:
|
||||||
|
```go
|
||||||
|
namespacesParam := r.URL.Query().Get("namespaces")
|
||||||
|
var namespaces []string
|
||||||
|
if namespacesParam != "" {
|
||||||
|
namespaces = strings.Split(namespacesParam, ",")
|
||||||
|
}
|
||||||
|
lc := logger.CreateClient(namespaces...)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Namespaces API handler** (`ws/namespaces.go`):
|
||||||
|
```go
|
||||||
|
func NamespacesHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
namespaces := logger.GetNamespaces()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"namespaces": namespaces,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Browser Package (`browser/`)
|
||||||
|
|
||||||
|
Still embeds viewer.html, but HTML now includes:
|
||||||
|
- Namespace filter input
|
||||||
|
- Namespace column in grid (5 columns instead of 4)
|
||||||
|
- `reconnectWithNamespace()` method
|
||||||
|
- WebSocket URL construction with query parameter
|
||||||
|
|
||||||
|
## Go Version & Dependencies
|
||||||
|
|
||||||
|
- **Go version**: 1.24.4 (specified in go.mod)
|
||||||
|
- **Only external dependency**: `github.com/gorilla/websocket v1.5.3`
|
||||||
|
|
||||||
|
## Naming Conventions & Style
|
||||||
|
|
||||||
|
### Namespaces
|
||||||
|
- Use lowercase strings: `"api"`, `"database"`, `"auth"`, `"cache"`
|
||||||
|
- Default constant: `DefaultNamespace = "default"`
|
||||||
|
- Comma-separated in query params: `?namespaces=api,database`
|
||||||
|
|
||||||
|
### Log Levels
|
||||||
|
Unchanged from v1 - still use uppercase strings and iota constants.
|
||||||
|
|
||||||
|
### Variable Names
|
||||||
|
- Use descriptive names (`apiLogger`, `dbLogger`, `namespaces`)
|
||||||
|
- Exception: Loop variables, short-lived scopes
|
||||||
|
|
||||||
|
## Important Patterns & Gotchas
|
||||||
|
|
||||||
|
### 1. Namespace Tracking is Automatic
|
||||||
|
When any log is created, its namespace is automatically added to the global registry:
|
||||||
|
```go
|
||||||
|
func createLog(e Entry) {
|
||||||
|
// Track namespace
|
||||||
|
namespacesMux.Lock()
|
||||||
|
namespaces[e.Namespace] = true
|
||||||
|
namespacesMux.Unlock()
|
||||||
|
// ... rest of function
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**No manual registration needed** - just log and the namespace appears.
|
||||||
|
|
||||||
|
### 2. Empty Namespace List = All Logs
|
||||||
|
Both for clients and WebSocket connections:
|
||||||
|
```go
|
||||||
|
client := log.CreateClient() // Gets ALL logs
|
||||||
|
ws://localhost:8080/ws // Gets ALL logs
|
||||||
|
```
|
||||||
|
|
||||||
|
This is the default behavior to maintain backward compatibility.
|
||||||
|
|
||||||
|
### 3. Client Namespace Filtering is Inclusive (OR)
|
||||||
|
If a client has multiple namespaces, it receives logs matching ANY of them:
|
||||||
|
```go
|
||||||
|
client := log.CreateClient("api", "database")
|
||||||
|
// Receives logs from "api" OR "database", not "auth"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Namespace Field Always Set
|
||||||
|
All logging functions set namespace:
|
||||||
|
- Package functions: `DefaultNamespace`
|
||||||
|
- Logger methods: `l.Namespace`
|
||||||
|
|
||||||
|
**Never nil or empty** - there's always a namespace.
|
||||||
|
|
||||||
|
### 5. WebSocket Namespace Reconnection
|
||||||
|
Changing namespace filter requires reconnecting WebSocket:
|
||||||
|
```javascript
|
||||||
|
reconnectWithNamespace() {
|
||||||
|
if (this.ws) {
|
||||||
|
this.ws.onclose = null; // Prevent auto-reconnect
|
||||||
|
this.ws.close();
|
||||||
|
this.ws = null;
|
||||||
|
}
|
||||||
|
this.reconnectAttempts = 0;
|
||||||
|
this.connectWebSocket(); // Creates new connection with new filter
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
UI provides "Reconnect" button for this purpose.
|
||||||
|
|
||||||
|
### 6. Stderr Client Uses All Namespaces
|
||||||
|
The built-in stderr client (created in `init()`) listens to all namespaces:
|
||||||
|
```go
|
||||||
|
stderrClient = CreateClient(DefaultNamespace)
|
||||||
|
```
|
||||||
|
|
||||||
|
But only prints logs matching its own namespace in `logStdErr()`:
|
||||||
|
```go
|
||||||
|
if e.level >= c.LogLevel && c.matchesNamespace(e.Namespace) {
|
||||||
|
fmt.Fprintf(os.Stderr, "%s\t%s\t[%s]\t%s\t%s\n", ...)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**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
|
||||||
|
The log viewer grid changed from 4 to 5 columns:
|
||||||
|
```css
|
||||||
|
/* v1 */
|
||||||
|
grid-template-columns: 180px 80px 1fr 120px;
|
||||||
|
|
||||||
|
/* v2 */
|
||||||
|
grid-template-columns: 180px 80px 100px 1fr 120px;
|
||||||
|
```
|
||||||
|
|
||||||
|
Order: Timestamp, Level, Namespace, Message, Source
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
### Test Updates for v2
|
||||||
|
|
||||||
|
All `CreateClient()` calls in tests now pass namespace:
|
||||||
|
```go
|
||||||
|
// v1
|
||||||
|
c := CreateClient()
|
||||||
|
|
||||||
|
// v2
|
||||||
|
c := CreateClient("test")
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests verify namespace appears in output (see stderr format).
|
||||||
|
|
||||||
|
### Running Tests
|
||||||
|
```bash
|
||||||
|
go test -v ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
All existing tests pass with namespace support added.
|
||||||
|
|
||||||
|
## CI/CD
|
||||||
|
|
||||||
|
GitHub Actions workflow (`.github/workflows/ci.yaml`):
|
||||||
|
- Still uses Go 1.21 (should update to 1.24.4 to match go.mod)
|
||||||
|
- No changes needed for v2 functionality
|
||||||
|
|
||||||
|
## Common Tasks
|
||||||
|
|
||||||
|
### Adding a New Namespace
|
||||||
|
|
||||||
|
No code changes needed! Just create a logger:
|
||||||
|
```go
|
||||||
|
cacheLogger := log.NewLogger("cache")
|
||||||
|
cacheLogger.Info("Cache initialized")
|
||||||
|
```
|
||||||
|
|
||||||
|
Namespace automatically tracked and available via API.
|
||||||
|
|
||||||
|
### Creating Namespace-Specific Client
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Subscribe only to API logs
|
||||||
|
apiClient := log.CreateClient("api")
|
||||||
|
defer apiClient.Destroy()
|
||||||
|
|
||||||
|
for {
|
||||||
|
entry := apiClient.Get()
|
||||||
|
// Only receives logs from "api" namespace
|
||||||
|
processAPILog(entry)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Filtering WebSocket by Namespace
|
||||||
|
|
||||||
|
Frontend:
|
||||||
|
```javascript
|
||||||
|
// Set namespace filter
|
||||||
|
document.getElementById('namespaceFilter').value = 'api,database';
|
||||||
|
// Click reconnect button or call:
|
||||||
|
logViewer.reconnectWithNamespace();
|
||||||
|
```
|
||||||
|
|
||||||
|
Backend automatically creates filtered client based on query param.
|
||||||
|
|
||||||
|
### Getting All Active Namespaces
|
||||||
|
|
||||||
|
```go
|
||||||
|
namespaces := log.GetNamespaces()
|
||||||
|
// Returns: ["default", "api", "database", "auth", ...]
|
||||||
|
```
|
||||||
|
|
||||||
|
Or via HTTP:
|
||||||
|
```bash
|
||||||
|
GET /api/namespaces
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"namespaces": ["default", "api", "database", "auth"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migration from v1 to v2
|
||||||
|
|
||||||
|
### Import Paths
|
||||||
|
```go
|
||||||
|
// v1
|
||||||
|
import "github.com/taigrr/log-socket/log"
|
||||||
|
import "github.com/taigrr/log-socket/ws"
|
||||||
|
import "github.com/taigrr/log-socket/browser"
|
||||||
|
|
||||||
|
// v2
|
||||||
|
import "github.com/taigrr/log-socket/v2/log"
|
||||||
|
import "github.com/taigrr/log-socket/v2/ws"
|
||||||
|
import "github.com/taigrr/log-socket/v2/browser"
|
||||||
|
```
|
||||||
|
|
||||||
|
### CreateClient Calls
|
||||||
|
```go
|
||||||
|
// v1
|
||||||
|
client := log.CreateClient()
|
||||||
|
|
||||||
|
// v2 - same behavior
|
||||||
|
client := log.CreateClient() // Empty = all namespaces
|
||||||
|
|
||||||
|
// v2 - new filtering capability
|
||||||
|
client := log.CreateClient("api")
|
||||||
|
client := log.CreateClient("api", "database")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Default() Logger
|
||||||
|
```go
|
||||||
|
// v1
|
||||||
|
logger := log.Default()
|
||||||
|
|
||||||
|
// v2 - uses default namespace
|
||||||
|
logger := log.Default()
|
||||||
|
|
||||||
|
// v2 - new namespaced option
|
||||||
|
logger := log.NewLogger("api")
|
||||||
|
```
|
||||||
|
|
||||||
|
### WebSocket URL
|
||||||
|
```
|
||||||
|
v1: ws://host/ws
|
||||||
|
v2: ws://host/ws # All namespaces (backward compatible)
|
||||||
|
v2: ws://host/ws?namespaces=api # Filtered
|
||||||
|
v2: ws://host/ws?namespaces=api,database # Multiple
|
||||||
|
```
|
||||||
|
|
||||||
|
## Repository Context
|
||||||
|
|
||||||
|
- **License**: Check LICENSE file
|
||||||
|
- **Funding**: GitHub sponsors (.github/FUNDING.yml)
|
||||||
|
- **Open Source**: github.com/taigrr/log-socket
|
||||||
|
- **Version**: v2.x.x (major version bump for breaking changes)
|
||||||
|
|
||||||
|
## Future Agent Notes
|
||||||
|
|
||||||
|
- **v2 is a breaking change**: Major version bump follows Go modules convention
|
||||||
|
- Namespace support is the primary new feature
|
||||||
|
- Backward compatible behavior: empty namespace list = all logs
|
||||||
|
- Namespace tracking is automatic via global registry
|
||||||
|
- Web UI has been significantly updated for namespace support
|
||||||
|
- Possible bug: stderr client might need to use `CreateClient()` instead of `CreateClient(DefaultNamespace)` to see all logs
|
||||||
|
- All tests updated and passing
|
||||||
|
- Example in main.go demonstrates multiple namespaces
|
||||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
|||||||
Copyright (C) 2019-2022 by Tai Groot <tai@taigrr.com>
|
Copyright (C) 2019-2025 by Tai Groot <tai@taigrr.com>
|
||||||
|
|
||||||
Permission to use, copy, modify, and/or distribute this software for any
|
Permission to use, copy, modify, and/or distribute this software for any
|
||||||
purpose with or without fee is hereby granted.
|
purpose with or without fee is hereby granted.
|
||||||
|
|||||||
238
README.md
238
README.md
@@ -1,15 +1,233 @@
|
|||||||
log-socket
|
# Log Socket v2
|
||||||
==========
|
|
||||||
`log-socket` is a drop-in replacement for Go's `log` package that allows for streaming of logs via WebSockets.
|
A real-time log viewer with WebSocket support and namespace filtering, written in Go.
|
||||||
|
|
||||||
|
## What's New in v2
|
||||||
|
|
||||||
|
**Breaking Changes:**
|
||||||
|
- Module path changed to `github.com/taigrr/log-socket/v2`
|
||||||
|
- `CreateClient()` now accepts variadic `namespaces ...string` parameter
|
||||||
|
- `Logger` type now includes `Namespace` field
|
||||||
|
- New `NewLogger(namespace string)` constructor for namespaced loggers
|
||||||
|
|
||||||
|
**New Features:**
|
||||||
|
- **Namespace support**: Organize logs by namespace (api, database, auth, etc.)
|
||||||
|
- **Namespace filtering**: Subscribe to specific namespaces via WebSocket
|
||||||
|
- **Frontend namespace selector**: Filter logs by namespace in the web UI
|
||||||
|
- **Namespace API**: GET `/api/namespaces` to list all active namespaces
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Real-time log streaming via WebSocket
|
||||||
|
- Web-based log viewer with filtering capabilities
|
||||||
|
- **Namespace-based log organization**
|
||||||
|
- Support for multiple log levels (TRACE, DEBUG, INFO, WARN, ERROR, PANIC, FATAL)
|
||||||
|
- Color-coded log levels for better visibility
|
||||||
|
- Auto-scrolling with toggle option
|
||||||
|
- Log download functionality
|
||||||
|
- Log clearing capability
|
||||||
|
- File source tracking for each log entry
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
To install the library:
|
|
||||||
`go get github.com/taigrr/log-socket`
|
|
||||||
|
|
||||||
## Running
|
```bash
|
||||||
To run a demo of this library:
|
go install github.com/taigrr/log-socket/v2@latest
|
||||||
`go run main.go`
|
```
|
||||||
|
|
||||||
This demo will do a sample of every log type and push results to `0.0.0.0:8080`. Once running, you can open a browser and navigate to
|
## Quick Start
|
||||||
`0.0.0.0:8080` to see an example implementation of how logs are streamed.
|
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
logger "github.com/taigrr/log-socket/v2/log"
|
||||||
|
"github.com/taigrr/log-socket/v2/ws"
|
||||||
|
"github.com/taigrr/log-socket/v2/browser"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
defer logger.Flush()
|
||||||
|
|
||||||
|
// Set up HTTP handlers
|
||||||
|
http.HandleFunc("/ws", ws.LogSocketHandler)
|
||||||
|
http.HandleFunc("/api/namespaces", ws.NamespacesHandler)
|
||||||
|
http.HandleFunc("/", browser.LogSocketViewHandler)
|
||||||
|
|
||||||
|
// Use default namespace
|
||||||
|
logger.Info("Application started")
|
||||||
|
|
||||||
|
// Create namespaced loggers
|
||||||
|
apiLogger := logger.NewLogger("api")
|
||||||
|
dbLogger := logger.NewLogger("database")
|
||||||
|
|
||||||
|
apiLogger.Info("API server ready")
|
||||||
|
dbLogger.Debug("Database connected")
|
||||||
|
|
||||||
|
logger.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Starting the Server
|
||||||
|
|
||||||
|
```bash
|
||||||
|
log-socket
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, the server runs on `0.0.0.0:8080`. Specify a different address:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
log-socket -addr localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
### Web Interface
|
||||||
|
|
||||||
|
Open your browser and navigate to `http://localhost:8080`
|
||||||
|
|
||||||
|
**Namespace Filtering:**
|
||||||
|
- The namespace dropdown is automatically populated from `/api/namespaces`
|
||||||
|
- Select one or more namespaces to filter (hold Ctrl/Cmd to multi-select)
|
||||||
|
- Default is "All Namespaces" (shows everything)
|
||||||
|
- Click "Reconnect" to apply the filter
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
### Logging Interface
|
||||||
|
|
||||||
|
The package provides two ways to log:
|
||||||
|
|
||||||
|
#### 1. Package-level functions (default namespace)
|
||||||
|
|
||||||
|
```go
|
||||||
|
logger.Trace("trace message")
|
||||||
|
logger.Debug("debug message")
|
||||||
|
logger.Info("info message")
|
||||||
|
logger.Notice("notice message")
|
||||||
|
logger.Warn("warning message")
|
||||||
|
logger.Error("error message")
|
||||||
|
logger.Panic("panic message") // Logs and panics
|
||||||
|
logger.Fatal("fatal message") // Logs and exits
|
||||||
|
```
|
||||||
|
|
||||||
|
Each has formatted (`f`) and line (`ln`) variants:
|
||||||
|
```go
|
||||||
|
logger.Infof("User %s logged in", username)
|
||||||
|
logger.Infoln("This adds a newline")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. Namespaced loggers
|
||||||
|
|
||||||
|
```go
|
||||||
|
apiLogger := logger.NewLogger("api")
|
||||||
|
apiLogger.Info("Request received")
|
||||||
|
|
||||||
|
dbLogger := logger.NewLogger("database")
|
||||||
|
dbLogger.Warn("Slow query detected")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Creating Clients with Namespace Filters
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Listen to all namespaces
|
||||||
|
client := logger.CreateClient()
|
||||||
|
|
||||||
|
// Listen to specific namespace
|
||||||
|
client := logger.CreateClient("api")
|
||||||
|
|
||||||
|
// Listen to multiple namespaces
|
||||||
|
client := logger.CreateClient("api", "database", "auth")
|
||||||
|
```
|
||||||
|
|
||||||
|
### WebSocket API
|
||||||
|
|
||||||
|
#### Log Stream Endpoint
|
||||||
|
|
||||||
|
**URL:** `ws://localhost:8080/ws`
|
||||||
|
|
||||||
|
**Query Parameters:**
|
||||||
|
- `namespaces` (optional): Comma-separated list of namespaces to filter
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
```
|
||||||
|
ws://localhost:8080/ws # All namespaces
|
||||||
|
ws://localhost:8080/ws?namespaces=api # Only "api" namespace
|
||||||
|
ws://localhost:8080/ws?namespaces=api,database # Multiple namespaces
|
||||||
|
```
|
||||||
|
|
||||||
|
**Message Format:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"timestamp": "2024-11-10T15:42:49.777298-05:00",
|
||||||
|
"output": "API request received",
|
||||||
|
"file": "main.go:42",
|
||||||
|
"level": "INFO",
|
||||||
|
"namespace": "api"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Namespaces List Endpoint
|
||||||
|
|
||||||
|
**URL:** `GET http://localhost:8080/api/namespaces`
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"namespaces": ["default", "api", "database", "auth"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Web Interface Features
|
||||||
|
|
||||||
|
- **Namespace Dropdown**: Dynamically populated from `/api/namespaces`, multi-select support
|
||||||
|
- **Text Search**: Filter logs by content, level, namespace, or source file
|
||||||
|
- **Auto-scroll**: Toggle auto-scrolling with checkbox
|
||||||
|
- **Download**: Save all logs as a JSON file
|
||||||
|
- **Clear**: Remove all logs from the viewer
|
||||||
|
- **Color Coding**: Different log levels are color-coded
|
||||||
|
- **Reconnect**: Reconnect WebSocket with new namespace filter
|
||||||
|
|
||||||
|
## Migration from v1
|
||||||
|
|
||||||
|
### Import Path
|
||||||
|
|
||||||
|
```go
|
||||||
|
// v1
|
||||||
|
import "github.com/taigrr/log-socket/log"
|
||||||
|
|
||||||
|
// v2
|
||||||
|
import "github.com/taigrr/log-socket/v2/log"
|
||||||
|
```
|
||||||
|
|
||||||
|
### CreateClient Changes
|
||||||
|
|
||||||
|
```go
|
||||||
|
// v1
|
||||||
|
client := log.CreateClient()
|
||||||
|
|
||||||
|
// v2 - specify namespace(s) or leave empty for all
|
||||||
|
client := log.CreateClient() // All namespaces
|
||||||
|
client := log.CreateClient("api") // Single namespace
|
||||||
|
client := log.CreateClient("api", "db") // Multiple namespaces
|
||||||
|
```
|
||||||
|
|
||||||
|
### New Logger Constructor
|
||||||
|
|
||||||
|
```go
|
||||||
|
// v2 only - create namespaced logger
|
||||||
|
apiLogger := log.NewLogger("api")
|
||||||
|
apiLogger.Info("Message in api namespace")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- [gorilla/websocket](https://github.com/gorilla/websocket) for WebSocket support
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
The web interface is provided as an example implementation. Users are encouraged to customize it for their specific needs. The WebSocket endpoint (`/ws`) can be consumed by any WebSocket client.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
See LICENSE file for details.
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//go:embed viewer.html
|
||||||
|
var webpage string
|
||||||
|
|
||||||
func LogSocketViewHandler(w http.ResponseWriter, r *http.Request) {
|
func LogSocketViewHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
wsResource := r.Host + r.URL.Path
|
wsResource := r.Host + r.URL.Path
|
||||||
if r.TLS != nil {
|
if r.TLS != nil {
|
||||||
@@ -18,7 +21,4 @@ func LogSocketViewHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
homeTemplate.Execute(w, wsResource)
|
homeTemplate.Execute(w, wsResource)
|
||||||
}
|
}
|
||||||
|
|
||||||
//go:embed viewer.html
|
|
||||||
var webpage string
|
|
||||||
|
|
||||||
var homeTemplate = template.Must(template.New("").Parse(webpage))
|
var homeTemplate = template.Must(template.New("").Parse(webpage))
|
||||||
|
|||||||
BIN
browser/screenshot.png
Normal file
BIN
browser/screenshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 117 KiB |
@@ -1,196 +1,706 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
</head>
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<body>
|
<title>Log Viewer</title>
|
||||||
<center>
|
<style>
|
||||||
<input type="text" id="search" onkeyup="filterTable()" placeholder="Filter...">
|
:root {
|
||||||
<input type="checkbox" id="shouldScroll" checked>Enable Autoscroll<br>
|
--primary-color: #2196F3;
|
||||||
<table id="logHeaders" style="text-align:left; width:80%;" >
|
--error-color: #f44336;
|
||||||
<tbody>
|
--warning-color: #ff9800;
|
||||||
<tr class="header">
|
--success-color: #4caf50;
|
||||||
<th style="width:20%;">TimeStamp</th>
|
--info-color: #2196F3;
|
||||||
<th style="width:5%;">Level</th>
|
--debug-color: #9c27b0;
|
||||||
<th style="width:65%;">Output</th>
|
--trace-color: #607d8b;
|
||||||
<th style="width:10%;">Source</th>
|
--bg-primary: #ffffff;
|
||||||
</tr>
|
--bg-secondary: #f5f5f5;
|
||||||
</tbody>
|
--text-primary: #333333;
|
||||||
</table>
|
--text-secondary: #666666;
|
||||||
|
--border-color: #e0e0e0;
|
||||||
|
--shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
--shadow-hover: 0 4px 8px rgba(0,0,0,0.15);
|
||||||
|
}
|
||||||
|
|
||||||
<div id="tableWrapper">
|
* {
|
||||||
<table id="logs" style="text-align:left; width:100%;" >
|
box-sizing: border-box;
|
||||||
<tbody id="tbodylogs">
|
}
|
||||||
<tr class="header">
|
|
||||||
<th style="width:20%;"></th>
|
|
||||||
<th style="width:5%;"></th>
|
|
||||||
<th style="width:65%;"></th>
|
|
||||||
<th style="width:10%;"></th>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
</tbody>
|
body {
|
||||||
</table>
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
|
||||||
|
background-color: var(--bg-secondary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
max-width: 1400px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
background: var(--bg-primary);
|
||||||
|
padding: 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
margin: 0 0 20px 0;
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controls {
|
||||||
|
display: flex;
|
||||||
|
gap: 15px;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-container {
|
||||||
|
position: relative;
|
||||||
|
flex: 1;
|
||||||
|
min-width: 250px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 15px;
|
||||||
|
border: 2px solid var(--border-color);
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: border-color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--primary-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-container {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-container input[type="checkbox"] {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-container label {
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-container {
|
||||||
|
background: var(--bg-primary);
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
overflow: hidden;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-header {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
padding: 12px 0;
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 12px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 180px 80px 100px 1fr 120px;
|
||||||
|
gap: 15px;
|
||||||
|
padding: 10px 15px;
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
transition: background-color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-row:hover {
|
||||||
|
background-color: rgba(0,0,0,0.02);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 13px;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell.timestamp {
|
||||||
|
font-family: 'Monaco', 'Menlo', monospace;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell.level {
|
||||||
|
font-weight: 600;
|
||||||
|
text-align: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell.output {
|
||||||
|
font-family: 'Monaco', 'Menlo', monospace;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell.source {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-level-error { background-color: #ffebee; color: var(--error-color); }
|
||||||
|
.log-level-warn { background-color: #fff3e0; color: var(--warning-color); }
|
||||||
|
.log-level-info { background-color: #e3f2fd; color: var(--info-color); }
|
||||||
|
.log-level-debug { background-color: #f3e5f5; color: var(--debug-color); }
|
||||||
|
.log-level-trace { background-color: #eceff1; color: var(--trace-color); }
|
||||||
|
|
||||||
|
.log-viewer {
|
||||||
|
height: 60vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
overflow-x: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-viewer::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-viewer::-webkit-scrollbar-track {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-viewer::-webkit-scrollbar-thumb {
|
||||||
|
background: #ccc;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-viewer::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #999;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
justify-content: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
padding: 10px 20px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
text-decoration: none;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:hover {
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: var(--shadow-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:active {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: var(--primary-color);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background-color: var(--error-color);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-bar {
|
||||||
|
background: var(--bg-primary);
|
||||||
|
padding: 10px 20px;
|
||||||
|
border-radius: 6px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.connection-status {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-indicator {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background-color: var(--error-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-indicator.connected {
|
||||||
|
background-color: var(--success-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 40px 20px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state h3 {
|
||||||
|
margin: 0 0 10px 0;
|
||||||
|
font-size: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state p {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.container {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controls {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-row {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell.timestamp::before {
|
||||||
|
content: 'Time: ';
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell.level::before {
|
||||||
|
content: 'Level: ';
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-cell.source::before {
|
||||||
|
content: 'Source: ';
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-header {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<header class="header">
|
||||||
|
<h1>📊 Log Viewer</h1>
|
||||||
|
<div class="controls">
|
||||||
|
<div class="search-container">
|
||||||
|
<select
|
||||||
|
id="namespaceFilter"
|
||||||
|
class="search-input"
|
||||||
|
multiple
|
||||||
|
size="1"
|
||||||
|
aria-label="Filter by namespace"
|
||||||
|
>
|
||||||
|
<option value="">All Namespaces (loading...)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="search-container">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="search"
|
||||||
|
class="search-input"
|
||||||
|
placeholder="🔍 Filter logs..."
|
||||||
|
aria-label="Filter logs"
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="checkbox-container">
|
||||||
|
<input type="checkbox" id="shouldScroll" checked>
|
||||||
|
<label for="shouldScroll">Auto-scroll</label>
|
||||||
|
</div>
|
||||||
|
<button id="reconnectBtn" class="btn btn-primary">
|
||||||
|
🔄 Reconnect
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<br>
|
</header>
|
||||||
<input class="button" type="button" id="download" value="Download Logs" style="background-color:#3f51b5;"/>
|
|
||||||
<input class="button" type="button" id="delete" value="Delete Logs" style="background-color:#f44336"/>
|
|
||||||
</center>
|
|
||||||
</body>
|
|
||||||
<footer>
|
|
||||||
<style>
|
|
||||||
#tableWrapper{
|
|
||||||
overflow-y: scroll;
|
|
||||||
display: flow-root;
|
|
||||||
width: 80%;
|
|
||||||
height: 80vh;
|
|
||||||
}
|
|
||||||
td,tr{
|
|
||||||
height: min-content;
|
|
||||||
}
|
|
||||||
.button{
|
|
||||||
display: inline-block;
|
|
||||||
width: 5vw;
|
|
||||||
height: 5vh;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
<script>
|
|
||||||
var logTable = document.getElementById("logs");
|
|
||||||
var logTableB = document.getElementById("tbodylogs");
|
|
||||||
var ws = null;
|
|
||||||
var application = "demo-commit"
|
|
||||||
var logs = [];
|
|
||||||
function sleep(ms) {
|
|
||||||
return new Promise(resolve => setTimeout(resolve, ms));
|
|
||||||
}
|
|
||||||
function download(filename, text) {
|
|
||||||
var element = document.createElement('a');
|
|
||||||
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
|
|
||||||
element.setAttribute('download', filename);
|
|
||||||
element.style.display = 'none';
|
|
||||||
document.body.appendChild(element);
|
|
||||||
element.click();
|
|
||||||
document.body.removeChild(element);
|
|
||||||
}
|
|
||||||
function openSocket() {
|
|
||||||
if (ws) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
ws = new WebSocket("{{.}}");
|
|
||||||
ws.onclose = async function(evt) {
|
|
||||||
ws = null;
|
|
||||||
while(ws == null){
|
|
||||||
openSocket()
|
|
||||||
await sleep(5000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ws.onmessage = function(evt) {
|
|
||||||
var entry = JSON.parse(evt.data)
|
|
||||||
logs.push(entry)
|
|
||||||
var row = document.createElement('tr');
|
|
||||||
var ts = document.createElement('td');
|
|
||||||
var tst = document.createTextNode(entry.timestamp);
|
|
||||||
ts.appendChild(tst);
|
|
||||||
row.appendChild(ts);
|
|
||||||
var ts = document.createElement('td');
|
|
||||||
var tst = document.createTextNode(entry.level);
|
|
||||||
ts.appendChild(tst);
|
|
||||||
row.appendChild(ts);
|
|
||||||
var ts = document.createElement('td');
|
|
||||||
var tst = document.createTextNode(entry.output);
|
|
||||||
ts.appendChild(tst);
|
|
||||||
row.appendChild(ts);
|
|
||||||
var ts = document.createElement('td');
|
|
||||||
var tst = document.createTextNode(entry.file);
|
|
||||||
ts.appendChild(tst);
|
|
||||||
row.appendChild(ts);
|
|
||||||
var bg="";
|
|
||||||
switch(entry.level){
|
|
||||||
case "INFO":
|
|
||||||
bg="white";
|
|
||||||
break;
|
|
||||||
case "ERROR":
|
|
||||||
bg="#f44336";
|
|
||||||
break;
|
|
||||||
case "WARN":
|
|
||||||
bg="#fb8c00"
|
|
||||||
break;
|
|
||||||
case "TRACE":
|
|
||||||
bg="#E1F5FE"
|
|
||||||
break;
|
|
||||||
case "DEBUG":
|
|
||||||
bg="#B3E5FC"
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
bg="white"
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
row.style.backgroundColor=bg
|
|
||||||
logTableB.append(row)
|
|
||||||
filterTable()
|
|
||||||
}
|
|
||||||
ws.onerror = function(evt) {
|
|
||||||
if (evt != null && evt.data != null){
|
|
||||||
// handle error here
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function clearTable(){
|
|
||||||
if(!window.confirm("Are you sure you want to delete all logs?")){
|
|
||||||
return
|
|
||||||
}
|
|
||||||
logs = []
|
|
||||||
|
|
||||||
while (logTableB.childNodes.length > 1) {
|
<div class="log-container">
|
||||||
logTableB.removeChild(logTableB.childNodes[1]);
|
<div class="log-header">
|
||||||
|
<div class="log-row">
|
||||||
|
<div class="log-cell">Timestamp</div>
|
||||||
|
<div class="log-cell">Level</div>
|
||||||
|
<div class="log-cell">Namespace</div>
|
||||||
|
<div class="log-cell">Message</div>
|
||||||
|
<div class="log-cell">Source</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="logViewer" class="log-viewer">
|
||||||
|
<div id="emptyState" class="empty-state">
|
||||||
|
<h3>No logs yet</h3>
|
||||||
|
<p>Waiting for log entries...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
<button id="downloadBtn" class="btn btn-primary">
|
||||||
|
📥 Download Logs
|
||||||
|
</button>
|
||||||
|
<button id="clearBtn" class="btn btn-danger">
|
||||||
|
🗑️ Clear Logs
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="status-bar">
|
||||||
|
<div class="connection-status">
|
||||||
|
<span class="status-indicator" id="statusIndicator"></span>
|
||||||
|
<span id="connectionStatus">Connecting...</span>
|
||||||
|
</div>
|
||||||
|
<div id="logCount">0 logs</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
class LogViewer {
|
||||||
|
constructor() {
|
||||||
|
this.ws = null;
|
||||||
|
this.logs = [];
|
||||||
|
this.filteredLogs = [];
|
||||||
|
this.isConnected = false;
|
||||||
|
this.reconnectAttempts = 0;
|
||||||
|
this.maxReconnectAttempts = 5;
|
||||||
|
|
||||||
|
this.initializeElements();
|
||||||
|
this.attachEventListeners();
|
||||||
|
this.fetchNamespaces();
|
||||||
|
this.connectWebSocket();
|
||||||
|
this.startAutoScroll();
|
||||||
|
}
|
||||||
|
|
||||||
|
initializeElements() {
|
||||||
|
this.logViewer = document.getElementById('logViewer');
|
||||||
|
this.emptyState = document.getElementById('emptyState');
|
||||||
|
this.namespaceFilter = document.getElementById('namespaceFilter');
|
||||||
|
this.searchInput = document.getElementById('search');
|
||||||
|
this.scrollCheckbox = document.getElementById('shouldScroll');
|
||||||
|
this.downloadBtn = document.getElementById('downloadBtn');
|
||||||
|
this.clearBtn = document.getElementById('clearBtn');
|
||||||
|
this.reconnectBtn = document.getElementById('reconnectBtn');
|
||||||
|
this.statusIndicator = document.getElementById('statusIndicator');
|
||||||
|
this.connectionStatus = document.getElementById('connectionStatus');
|
||||||
|
this.logCount = document.getElementById('logCount');
|
||||||
|
}
|
||||||
|
|
||||||
|
attachEventListeners() {
|
||||||
|
this.searchInput.addEventListener('input', this.debounce(() => this.filterLogs(), 300));
|
||||||
|
this.namespaceFilter.addEventListener('change', () => this.reconnectWithNamespace());
|
||||||
|
this.downloadBtn.addEventListener('click', () => this.downloadLogs());
|
||||||
|
this.clearBtn.addEventListener('click', () => this.clearLogs());
|
||||||
|
this.reconnectBtn.addEventListener('click', () => this.reconnectWithNamespace());
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchNamespaces() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/namespaces');
|
||||||
|
const data = await response.json();
|
||||||
|
this.updateNamespaceFilter(data.namespaces || []);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch namespaces:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function filterTable() {
|
|
||||||
var cols, input, filter, table, tr, td, i, txtValue, w;
|
updateNamespaceFilter(namespaces) {
|
||||||
input = document.getElementById("search");
|
// Clear existing options
|
||||||
filter = input.value;
|
this.namespaceFilter.innerHTML = '';
|
||||||
table = logTableB;
|
|
||||||
tr = table.getElementsByTagName("tr");
|
// Add "All" option
|
||||||
for (i = 1; i < tr.length; i++) {
|
const allOption = document.createElement('option');
|
||||||
cols = tr[i].getElementsByTagName("td");
|
allOption.value = '';
|
||||||
var visible = false;
|
allOption.textContent = 'All Namespaces';
|
||||||
for (w = 0; w < cols.length; w++){
|
allOption.selected = true;
|
||||||
if (!visible && cols[w]) {
|
this.namespaceFilter.appendChild(allOption);
|
||||||
td = cols[w]
|
|
||||||
txtValue = td.textContent || td.innerText;
|
// Add namespace options
|
||||||
if (txtValue.indexOf(filter) > -1) {
|
namespaces.sort().forEach(ns => {
|
||||||
visible = true
|
const option = document.createElement('option');
|
||||||
}
|
option.value = ns;
|
||||||
|
option.textContent = ns;
|
||||||
|
this.namespaceFilter.appendChild(option);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
connectWebSocket() {
|
||||||
|
if (this.ws) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let wsUrl = "{{.}}";
|
||||||
|
|
||||||
|
// Get selected namespace options from multi-select
|
||||||
|
const selectedOptions = Array.from(this.namespaceFilter.selectedOptions)
|
||||||
|
.map(opt => opt.value)
|
||||||
|
.filter(val => val !== ''); // Remove empty "All" option
|
||||||
|
|
||||||
|
// Add namespace filter if specific namespaces selected
|
||||||
|
if (selectedOptions.length > 0) {
|
||||||
|
const namespaces = selectedOptions.join(',');
|
||||||
|
const separator = wsUrl.includes('?') ? '&' : '?';
|
||||||
|
wsUrl += `${separator}namespaces=${encodeURIComponent(namespaces)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ws = new WebSocket(wsUrl);
|
||||||
|
this.updateConnectionStatus('Connecting...', false);
|
||||||
|
|
||||||
|
this.ws.onopen = () => {
|
||||||
|
this.isConnected = true;
|
||||||
|
this.reconnectAttempts = 0;
|
||||||
|
this.updateConnectionStatus('Connected', true);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.ws.onmessage = (event) => {
|
||||||
|
try {
|
||||||
|
const logEntry = JSON.parse(event.data);
|
||||||
|
this.addLogEntry(logEntry);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to parse log entry:', error);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
if(visible){
|
|
||||||
|
|
||||||
tr[i].style.display = "";
|
this.ws.onclose = () => {
|
||||||
} else {
|
this.isConnected = false;
|
||||||
|
this.ws = null;
|
||||||
|
this.updateConnectionStatus('Disconnected', false);
|
||||||
|
this.scheduleReconnect();
|
||||||
|
};
|
||||||
|
|
||||||
tr[i].style.display = "none";
|
this.ws.onerror = (error) => {
|
||||||
}
|
console.error('WebSocket error:', error);
|
||||||
|
this.updateConnectionStatus('Connection Error', false);
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to create WebSocket:', error);
|
||||||
|
this.updateConnectionStatus('Connection Failed', false);
|
||||||
|
this.scheduleReconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function pageScroll() {
|
|
||||||
if (document.getElementById('shouldScroll').checked) {
|
|
||||||
document.getElementById('tableWrapper').scrollBy(0,10);
|
|
||||||
|
|
||||||
|
reconnectWithNamespace() {
|
||||||
|
if (this.ws) {
|
||||||
|
this.ws.onclose = null; // Prevent auto-reconnect
|
||||||
|
this.ws.close();
|
||||||
|
this.ws = null;
|
||||||
}
|
}
|
||||||
setTimeout(pageScroll,10);
|
this.reconnectAttempts = 0;
|
||||||
|
this.connectWebSocket();
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById("delete").addEventListener("click", function(){
|
scheduleReconnect() {
|
||||||
|
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||||
|
this.reconnectAttempts++;
|
||||||
|
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
|
||||||
|
|
||||||
|
this.updateConnectionStatus(`Reconnecting in ${Math.ceil(delay/1000)}s...`, false);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
this.connectWebSocket();
|
||||||
|
}, delay);
|
||||||
|
} else {
|
||||||
|
this.updateConnectionStatus('Connection Failed', false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
clearTable()
|
addLogEntry(entry) {
|
||||||
}, false);
|
this.logs.push(entry);
|
||||||
document.getElementById("download").addEventListener("click", function(){
|
this.updateLogCount();
|
||||||
|
|
||||||
|
if (this.matchesFilter(entry)) {
|
||||||
|
this.renderLogEntry(entry);
|
||||||
|
this.hideEmptyState();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
download(application+'.json',JSON.stringify(logs));
|
renderLogEntry(entry) {
|
||||||
}, false);
|
const logRow = document.createElement('div');
|
||||||
openSocket();
|
logRow.className = `log-row log-level-${entry.level.toLowerCase()}`;
|
||||||
pageScroll();
|
|
||||||
</script>
|
logRow.innerHTML = `
|
||||||
|
<div class="log-cell timestamp">${this.formatTimestamp(entry.timestamp)}</div>
|
||||||
|
<div class="log-cell level">${entry.level}</div>
|
||||||
|
<div class="log-cell namespace">${this.escapeHtml(entry.namespace || 'default')}</div>
|
||||||
|
<div class="log-cell output">${this.escapeHtml(entry.output)}</div>
|
||||||
|
<div class="log-cell source">${this.escapeHtml(entry.file || 'N/A')}</div>
|
||||||
|
`;
|
||||||
|
|
||||||
</footer>
|
this.logViewer.appendChild(logRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
formatTimestamp(timestamp) {
|
||||||
|
try {
|
||||||
|
const date = new Date(timestamp);
|
||||||
|
return date.toLocaleString();
|
||||||
|
} catch {
|
||||||
|
return timestamp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
escapeHtml(text) {
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.textContent = text;
|
||||||
|
return div.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
filterLogs() {
|
||||||
|
const query = this.searchInput.value.toLowerCase().trim();
|
||||||
|
|
||||||
|
// Clear current display
|
||||||
|
this.clearLogDisplay();
|
||||||
|
|
||||||
|
if (!query) {
|
||||||
|
// Show all logs
|
||||||
|
this.logs.forEach(log => this.renderLogEntry(log));
|
||||||
|
} else {
|
||||||
|
// Show filtered logs
|
||||||
|
const filtered = this.logs.filter(log =>
|
||||||
|
this.matchesQuery(log, query)
|
||||||
|
);
|
||||||
|
filtered.forEach(log => this.renderLogEntry(log));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.logViewer.children.length === 0 ||
|
||||||
|
(this.logViewer.children.length === 1 && this.logViewer.contains(this.emptyState))) {
|
||||||
|
this.showEmptyState();
|
||||||
|
} else {
|
||||||
|
this.hideEmptyState();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
matchesFilter(entry) {
|
||||||
|
const query = this.searchInput.value.toLowerCase().trim();
|
||||||
|
return !query || this.matchesQuery(entry, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
matchesQuery(entry, query) {
|
||||||
|
return (
|
||||||
|
entry.output.toLowerCase().includes(query) ||
|
||||||
|
entry.level.toLowerCase().includes(query) ||
|
||||||
|
(entry.namespace && entry.namespace.toLowerCase().includes(query)) ||
|
||||||
|
(entry.file && entry.file.toLowerCase().includes(query)) ||
|
||||||
|
entry.timestamp.toLowerCase().includes(query)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
clearLogDisplay() {
|
||||||
|
while (this.logViewer.firstChild && this.logViewer.firstChild !== this.emptyState) {
|
||||||
|
this.logViewer.removeChild(this.logViewer.firstChild);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
showEmptyState() {
|
||||||
|
if (!this.logViewer.contains(this.emptyState)) {
|
||||||
|
this.logViewer.appendChild(this.emptyState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hideEmptyState() {
|
||||||
|
if (this.logViewer.contains(this.emptyState)) {
|
||||||
|
this.logViewer.removeChild(this.emptyState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
clearLogs() {
|
||||||
|
if (!confirm('Are you sure you want to clear all logs?')) return;
|
||||||
|
|
||||||
|
this.logs = [];
|
||||||
|
this.clearLogDisplay();
|
||||||
|
this.showEmptyState();
|
||||||
|
this.updateLogCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
downloadLogs() {
|
||||||
|
if (this.logs.length === 0) {
|
||||||
|
alert('No logs to download');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dataStr = JSON.stringify(this.logs, null, 2);
|
||||||
|
const dataBlob = new Blob([dataStr], { type: 'application/json' });
|
||||||
|
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = URL.createObjectURL(dataBlob);
|
||||||
|
link.download = `logs-${new Date().toISOString().split('T')[0]}.json`;
|
||||||
|
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
|
||||||
|
URL.revokeObjectURL(link.href);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateConnectionStatus(status, connected) {
|
||||||
|
this.connectionStatus.textContent = status;
|
||||||
|
this.statusIndicator.classList.toggle('connected', connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateLogCount() {
|
||||||
|
const count = this.logs.length;
|
||||||
|
this.logCount.textContent = `${count} log${count !== 1 ? 's' : ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
startAutoScroll() {
|
||||||
|
const autoScroll = () => {
|
||||||
|
if (this.scrollCheckbox.checked && this.isConnected) {
|
||||||
|
this.logViewer.scrollTop = this.logViewer.scrollHeight;
|
||||||
|
}
|
||||||
|
requestAnimationFrame(autoScroll);
|
||||||
|
};
|
||||||
|
autoScroll();
|
||||||
|
}
|
||||||
|
|
||||||
|
debounce(func, wait) {
|
||||||
|
let timeout;
|
||||||
|
return function executedFunction(...args) {
|
||||||
|
const later = () => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
func(...args);
|
||||||
|
};
|
||||||
|
clearTimeout(timeout);
|
||||||
|
timeout = setTimeout(later, wait);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize the log viewer when the page loads
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
new LogViewer();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
6
go.mod
6
go.mod
@@ -1,5 +1,5 @@
|
|||||||
module github.com/taigrr/log-socket
|
module github.com/taigrr/log-socket/v2
|
||||||
|
|
||||||
go 1.16
|
go 1.25.4
|
||||||
|
|
||||||
require github.com/gorilla/websocket v1.5.0
|
require github.com/gorilla/websocket v1.5.3
|
||||||
|
|||||||
4
go.sum
4
go.sum
@@ -1,2 +1,2 @@
|
|||||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
|||||||
389
log/benchmark_test.go
Normal file
389
log/benchmark_test.go
Normal file
@@ -0,0 +1,389 @@
|
|||||||
|
package log
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// drainClient continuously reads from a client to prevent blocking.
|
||||||
|
// Returns a function to stop draining and wait for completion.
|
||||||
|
func drainClient(c *Client) func() {
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return
|
||||||
|
case <-c.writer:
|
||||||
|
// Drain entries
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return func() { close(done) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Serial Benchmarks - Single Log Levels
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func BenchmarkTrace(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LTrace)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Trace("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkDebug(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LDebug)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Debug("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkInfo(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Info("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkNotice(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LNotice)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Notice("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkWarn(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LWarn)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Warn("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkError(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LError)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Error("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Formatted Logging Benchmarks
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func BenchmarkDebugf(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LDebug)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Debugf("benchmark message %d with %s", i, "formatting")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkInfof(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Infof("benchmark message %d with %s", i, "formatting")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkErrorf(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LError)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Errorf("benchmark message %d with %s", i, "formatting")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Parallel Benchmarks
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func BenchmarkDebugParallel(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LDebug)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
b.RunParallel(func(pb *testing.PB) {
|
||||||
|
for pb.Next() {
|
||||||
|
Debug("parallel benchmark message")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkInfoParallel(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
b.RunParallel(func(pb *testing.PB) {
|
||||||
|
for pb.Next() {
|
||||||
|
Info("parallel benchmark message")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkInfofParallel(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
b.RunParallel(func(pb *testing.PB) {
|
||||||
|
counter := 0
|
||||||
|
for pb.Next() {
|
||||||
|
Infof("parallel benchmark message %d", counter)
|
||||||
|
counter++
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Logger Instance Benchmarks (Namespaced Logging)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func BenchmarkLoggerInfo(b *testing.B) {
|
||||||
|
logger := NewLogger("benchmark")
|
||||||
|
c := CreateClient("benchmark")
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
logger.Info("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkLoggerInfof(b *testing.B) {
|
||||||
|
logger := NewLogger("benchmark")
|
||||||
|
c := CreateClient("benchmark")
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
logger.Infof("benchmark message %d", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkLoggerDebugParallel(b *testing.B) {
|
||||||
|
logger := NewLogger("benchmark")
|
||||||
|
c := CreateClient("benchmark")
|
||||||
|
c.SetLogLevel(LDebug)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
b.RunParallel(func(pb *testing.PB) {
|
||||||
|
for pb.Next() {
|
||||||
|
logger.Debug("parallel benchmark message")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Multiple Client Benchmarks
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func BenchmarkMultipleClients(b *testing.B) {
|
||||||
|
const numClients = 5
|
||||||
|
var clients []*Client
|
||||||
|
var stopFuncs []func()
|
||||||
|
|
||||||
|
for i := 0; i < numClients; i++ {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
clients = append(clients, c)
|
||||||
|
stopFuncs = append(stopFuncs, stop)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
for i, c := range clients {
|
||||||
|
stopFuncs[i]()
|
||||||
|
c.Destroy()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Info("benchmark message to multiple clients")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkMultipleNamespaces(b *testing.B) {
|
||||||
|
namespaces := []string{"auth", "db", "api", "cache", "queue"}
|
||||||
|
var loggers []*Logger
|
||||||
|
var clients []*Client
|
||||||
|
var stopFuncs []func()
|
||||||
|
|
||||||
|
for _, ns := range namespaces {
|
||||||
|
loggers = append(loggers, NewLogger(ns))
|
||||||
|
c := CreateClient(ns)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
clients = append(clients, c)
|
||||||
|
stopFuncs = append(stopFuncs, stop)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
for i, c := range clients {
|
||||||
|
stopFuncs[i]()
|
||||||
|
c.Destroy()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
loggers[i%len(loggers)].Info("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// With Synchronous Client Consumption (Legacy Pattern)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// BenchmarkDebugWithSyncConsumer measures the overhead of synchronous consumption
|
||||||
|
// using the Get() method, processing one message at a time.
|
||||||
|
func BenchmarkDebugWithSyncConsumer(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LDebug)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
// This benchmark measures just the logging side with async draining.
|
||||||
|
// For sync consumption patterns, see the TestOrder test.
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Debug("benchmark message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Comparison Benchmarks (Different Message Sizes)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func BenchmarkInfoShortMessage(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Info("ok")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkInfoMediumMessage(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
msg := "This is a medium-length log message for benchmarking purposes"
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Info(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkInfoLongMessage(b *testing.B) {
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LInfo)
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
msg := "This is a much longer log message that simulates real-world logging scenarios where developers tend to include more context about what the application is doing, including variable values, request IDs, and other debugging information that can be quite verbose"
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Info(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Overhead Benchmarks (Level Filtering)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func BenchmarkDebugFilteredByLevel(b *testing.B) {
|
||||||
|
// No client with Debug level, so Debug logs won't be consumed
|
||||||
|
// This measures the overhead of creating log entries that get filtered
|
||||||
|
c := CreateClient(DefaultNamespace)
|
||||||
|
c.SetLogLevel(LError) // Only Error and above
|
||||||
|
stop := drainClient(c)
|
||||||
|
defer stop()
|
||||||
|
defer c.Destroy()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
Debug("this message will be filtered")
|
||||||
|
}
|
||||||
|
}
|
||||||
124
log/log.go
124
log/log.go
@@ -16,10 +16,13 @@ var (
|
|||||||
stderrClient *Client
|
stderrClient *Client
|
||||||
cleanup sync.Once
|
cleanup sync.Once
|
||||||
stderrFinished chan bool
|
stderrFinished chan bool
|
||||||
|
namespaces map[string]bool
|
||||||
|
namespacesMux sync.RWMutex
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
stderrClient = CreateClient()
|
namespaces = make(map[string]bool)
|
||||||
|
stderrClient = CreateClient(DefaultNamespace)
|
||||||
stderrClient.SetLogLevel(LTrace)
|
stderrClient.SetLogLevel(LTrace)
|
||||||
stderrFinished = make(chan bool, 1)
|
stderrFinished = make(chan bool, 1)
|
||||||
go stderrClient.logStdErr()
|
go stderrClient.logStdErr()
|
||||||
@@ -27,16 +30,30 @@ 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 {
|
if e.level >= c.LogLevel && c.matchesNamespace(e.Namespace) {
|
||||||
fmt.Fprintf(os.Stderr, "%s\t%s\t%s\t%s\n", e.Timestamp.String(), e.Level, e.Output, e.File)
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
stderrFinished <- true
|
stderrFinished <- true
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateClient() *Client {
|
func (c *Client) matchesNamespace(namespace string) bool {
|
||||||
|
// Empty Namespaces slice means match all
|
||||||
|
if len(c.Namespaces) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, ns := range c.Namespaces {
|
||||||
|
if ns == namespace {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateClient(namespaces ...string) *Client {
|
||||||
var client Client
|
var client Client
|
||||||
client.initialized = true
|
client.initialized = true
|
||||||
|
client.Namespaces = namespaces
|
||||||
client.writer = make(LogWriter, 1000)
|
client.writer = make(LogWriter, 1000)
|
||||||
sliceTex.Lock()
|
sliceTex.Lock()
|
||||||
clients = append(clients, &client)
|
clients = append(clients, &client)
|
||||||
@@ -78,9 +95,18 @@ func (c *Client) GetLogLevel() Level {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func createLog(e Entry) {
|
func createLog(e Entry) {
|
||||||
|
// Track namespace
|
||||||
|
namespacesMux.Lock()
|
||||||
|
namespaces[e.Namespace] = true
|
||||||
|
namespacesMux.Unlock()
|
||||||
|
|
||||||
sliceTex.Lock()
|
sliceTex.Lock()
|
||||||
for _, c := range clients {
|
for _, c := range clients {
|
||||||
func(c *Client, e Entry) {
|
func(c *Client, e Entry) {
|
||||||
|
// Filter by namespace if client has filters specified
|
||||||
|
if !c.matchesNamespace(e.Namespace) {
|
||||||
|
return
|
||||||
|
}
|
||||||
select {
|
select {
|
||||||
case c.writer <- e:
|
case c.writer <- e:
|
||||||
// try to clear out one of the older entries
|
// try to clear out one of the older entries
|
||||||
@@ -96,6 +122,18 @@ func createLog(e Entry) {
|
|||||||
sliceTex.Unlock()
|
sliceTex.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNamespaces returns a list of all namespaces that have been used
|
||||||
|
func GetNamespaces() []string {
|
||||||
|
namespacesMux.RLock()
|
||||||
|
defer namespacesMux.RUnlock()
|
||||||
|
|
||||||
|
result := make([]string, 0, len(namespaces))
|
||||||
|
for ns := range namespaces {
|
||||||
|
result = append(result, ns)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
func SetLogLevel(level Level) {
|
func SetLogLevel(level Level) {
|
||||||
stderrClient.LogLevel = level
|
stderrClient.LogLevel = level
|
||||||
}
|
}
|
||||||
@@ -116,20 +154,21 @@ func (c *Client) Get() Entry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Trace prints out logs on trace level
|
// Trace prints out logs on trace level
|
||||||
func Trace(args ...interface{}) {
|
func Trace(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Output: output,
|
Output: output,
|
||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Trace
|
// Formatted print for Trace
|
||||||
func Tracef(format string, args ...interface{}) {
|
func Tracef(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -137,12 +176,13 @@ func Tracef(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trace prints out logs on trace level with newline
|
// Trace prints out logs on trace level with newline
|
||||||
func Traceln(args ...interface{}) {
|
func Traceln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -150,12 +190,13 @@ func Traceln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Debug prints out logs on debug level
|
// Debug prints out logs on debug level
|
||||||
func Debug(args ...interface{}) {
|
func Debug(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -163,12 +204,13 @@ func Debug(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "DEBUG",
|
Level: "DEBUG",
|
||||||
level: LDebug,
|
level: LDebug,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Debug
|
// Formatted print for Debug
|
||||||
func Debugf(format string, args ...interface{}) {
|
func Debugf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -176,12 +218,13 @@ func Debugf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "DEBUG",
|
Level: "DEBUG",
|
||||||
level: LDebug,
|
level: LDebug,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Debug prints out logs on debug level with a newline
|
// Debug prints out logs on debug level with a newline
|
||||||
func Debugln(args ...interface{}) {
|
func Debugln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -189,12 +232,13 @@ func Debugln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "DEBUG",
|
Level: "DEBUG",
|
||||||
level: LDebug,
|
level: LDebug,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info prints out logs on info level
|
// Info prints out logs on info level
|
||||||
func Info(args ...interface{}) {
|
func Info(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -202,12 +246,13 @@ func Info(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Info
|
// Formatted print for Info
|
||||||
func Infof(format string, args ...interface{}) {
|
func Infof(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -215,12 +260,13 @@ func Infof(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info prints out logs on info level with a newline
|
// Info prints out logs on info level with a newline
|
||||||
func Infoln(args ...interface{}) {
|
func Infoln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -228,12 +274,13 @@ func Infoln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info prints out logs on info level
|
// Info prints out logs on info level
|
||||||
func Notice(args ...interface{}) {
|
func Notice(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -241,12 +288,13 @@ func Notice(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Info
|
// Formatted print for Info
|
||||||
func Noticef(format string, args ...interface{}) {
|
func Noticef(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -254,12 +302,13 @@ func Noticef(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info prints out logs on info level with a newline
|
// Info prints out logs on info level with a newline
|
||||||
func Noticeln(args ...interface{}) {
|
func Noticeln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -267,12 +316,13 @@ func Noticeln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Warn prints out logs on warn level
|
// Warn prints out logs on warn level
|
||||||
func Warn(args ...interface{}) {
|
func Warn(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -280,12 +330,13 @@ func Warn(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Warn
|
// Formatted print for Warn
|
||||||
func Warnf(format string, args ...interface{}) {
|
func Warnf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -293,12 +344,13 @@ func Warnf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Newline print for Warn
|
// Newline print for Warn
|
||||||
func Warnln(args ...interface{}) {
|
func Warnln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -306,12 +358,13 @@ func Warnln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error prints out logs on error level
|
// Error prints out logs on error level
|
||||||
func Error(args ...interface{}) {
|
func Error(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -319,12 +372,13 @@ func Error(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for error
|
// Formatted print for error
|
||||||
func Errorf(format string, args ...interface{}) {
|
func Errorf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -332,12 +386,13 @@ func Errorf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error prints out logs on error level with a newline
|
// Error prints out logs on error level with a newline
|
||||||
func Errorln(args ...interface{}) {
|
func Errorln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -345,12 +400,13 @@ func Errorln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Panic prints out logs on panic level
|
// Panic prints out logs on panic level
|
||||||
func Panic(args ...interface{}) {
|
func Panic(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -358,6 +414,7 @@ func Panic(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) >= 0 {
|
if len(args) >= 0 {
|
||||||
@@ -373,7 +430,7 @@ func Panic(args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for panic
|
// Formatted print for panic
|
||||||
func Panicf(format string, args ...interface{}) {
|
func Panicf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -381,6 +438,7 @@ func Panicf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) >= 0 {
|
if len(args) >= 0 {
|
||||||
@@ -395,7 +453,7 @@ func Panicf(format string, args ...interface{}) {
|
|||||||
panic(errors.New(output))
|
panic(errors.New(output))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Panicln(args ...interface{}) {
|
func Panicln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -403,6 +461,7 @@ func Panicln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) >= 0 {
|
if len(args) >= 0 {
|
||||||
@@ -418,7 +477,7 @@ func Panicln(args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fatal prints out logs on fatal level
|
// Fatal prints out logs on fatal level
|
||||||
func Fatal(args ...interface{}) {
|
func Fatal(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -426,6 +485,7 @@ func Fatal(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
Flush()
|
Flush()
|
||||||
@@ -433,7 +493,7 @@ func Fatal(args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for fatal
|
// Formatted print for fatal
|
||||||
func Fatalf(format string, args ...interface{}) {
|
func Fatalf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -441,13 +501,14 @@ func Fatalf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
Flush()
|
Flush()
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Fatalln(args ...interface{}) {
|
func Fatalln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -455,21 +516,22 @@ func Fatalln(args ...interface{}) {
|
|||||||
File: fileInfo(2),
|
File: fileInfo(2),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
|
Namespace: DefaultNamespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
Flush()
|
Flush()
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Print(args ...interface{}) {
|
func Print(args ...any) {
|
||||||
Info(args...)
|
Info(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Printf(format string, args ...interface{}) {
|
func Printf(format string, args ...any) {
|
||||||
Infof(format, args...)
|
Infof(format, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Println(args ...interface{}) {
|
func Println(args ...any) {
|
||||||
Infoln(args...)
|
Infoln(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package log
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,7 +12,7 @@ func TestCreateDestroy(t *testing.T) {
|
|||||||
t.Errorf("Expected 1 client, but found %d", len(clients))
|
t.Errorf("Expected 1 client, but found %d", len(clients))
|
||||||
}
|
}
|
||||||
// Create a new client, ensure it's added
|
// Create a new client, ensure it's added
|
||||||
c := CreateClient()
|
c := CreateClient("test")
|
||||||
if len(clients) != 2 {
|
if len(clients) != 2 {
|
||||||
t.Errorf("Expected 2 clients, but found %d", len(clients))
|
t.Errorf("Expected 2 clients, but found %d", len(clients))
|
||||||
}
|
}
|
||||||
@@ -27,7 +26,7 @@ func TestCreateDestroy(t *testing.T) {
|
|||||||
// SetLogLevel set log level of logger
|
// SetLogLevel set log level of logger
|
||||||
func TestSetLogLevel(t *testing.T) {
|
func TestSetLogLevel(t *testing.T) {
|
||||||
logLevels := [...]Level{LTrace, LDebug, LInfo, LWarn, LError, LPanic, LFatal}
|
logLevels := [...]Level{LTrace, LDebug, LInfo, LWarn, LError, LPanic, LFatal}
|
||||||
c := CreateClient()
|
c := CreateClient("test")
|
||||||
for _, x := range logLevels {
|
for _, x := range logLevels {
|
||||||
c.SetLogLevel(x)
|
c.SetLogLevel(x)
|
||||||
if c.GetLogLevel() != x {
|
if c.GetLogLevel() != x {
|
||||||
@@ -37,25 +36,10 @@ func TestSetLogLevel(t *testing.T) {
|
|||||||
c.Destroy()
|
c.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkDebugSerial(b *testing.B) {
|
|
||||||
c := CreateClient()
|
|
||||||
var x sync.WaitGroup
|
|
||||||
x.Add(b.N)
|
|
||||||
for i := 0; i < b.N; i++ {
|
|
||||||
Debug(i)
|
|
||||||
go func() {
|
|
||||||
c.Get()
|
|
||||||
x.Done()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
x.Wait()
|
|
||||||
c.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Trace ensure logs come out in the right order
|
// Trace ensure logs come out in the right order
|
||||||
func TestOrder(t *testing.T) {
|
func TestOrder(t *testing.T) {
|
||||||
testString := "Testing trace: "
|
testString := "Testing trace: "
|
||||||
c := CreateClient()
|
c := CreateClient(DefaultNamespace)
|
||||||
c.SetLogLevel(LTrace)
|
c.SetLogLevel(LTrace)
|
||||||
|
|
||||||
for i := 0; i < 5000; i++ {
|
for i := 0; i < 5000; i++ {
|
||||||
|
|||||||
@@ -7,12 +7,23 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func Default() *Logger {
|
||||||
|
return &Logger{FileInfoDepth: 0, Namespace: DefaultNamespace}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLogger(namespace string) *Logger {
|
||||||
|
if namespace == "" {
|
||||||
|
namespace = DefaultNamespace
|
||||||
|
}
|
||||||
|
return &Logger{FileInfoDepth: 0, Namespace: namespace}
|
||||||
|
}
|
||||||
|
|
||||||
func (l *Logger) SetInfoDepth(depth int) {
|
func (l *Logger) SetInfoDepth(depth int) {
|
||||||
l.FileInfoDepth = depth
|
l.FileInfoDepth = depth
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trace prints out logs on trace level
|
// Trace prints out logs on trace level
|
||||||
func (l Logger) Trace(args ...interface{}) {
|
func (l Logger) Trace(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -20,12 +31,13 @@ func (l Logger) Trace(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Trace
|
// Formatted print for Trace
|
||||||
func (l Logger) Tracef(format string, args ...interface{}) {
|
func (l Logger) Tracef(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -33,12 +45,13 @@ func (l Logger) Tracef(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trace prints out logs on trace level with newline
|
// Trace prints out logs on trace level with newline
|
||||||
func (l Logger) Traceln(args ...interface{}) {
|
func (l Logger) Traceln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -46,12 +59,13 @@ func (l Logger) Traceln(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "TRACE",
|
Level: "TRACE",
|
||||||
level: LTrace,
|
level: LTrace,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Debug prints out logs on debug level
|
// Debug prints out logs on debug level
|
||||||
func (l Logger) Debug(args ...interface{}) {
|
func (l Logger) Debug(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -59,12 +73,13 @@ func (l Logger) Debug(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "DEBUG",
|
Level: "DEBUG",
|
||||||
level: LDebug,
|
level: LDebug,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Debug
|
// Formatted print for Debug
|
||||||
func (l Logger) Debugf(format string, args ...interface{}) {
|
func (l Logger) Debugf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -72,12 +87,13 @@ func (l Logger) Debugf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "DEBUG",
|
Level: "DEBUG",
|
||||||
level: LDebug,
|
level: LDebug,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info prints out logs on info level
|
// Info prints out logs on info level
|
||||||
func (l Logger) Info(args ...interface{}) {
|
func (l Logger) Info(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -85,12 +101,13 @@ func (l Logger) Info(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Info
|
// Formatted print for Info
|
||||||
func (l Logger) Infof(format string, args ...interface{}) {
|
func (l Logger) Infof(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -98,12 +115,13 @@ func (l Logger) Infof(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Info prints out logs on info level with newline
|
// Info prints out logs on info level with newline
|
||||||
func (l Logger) Infoln(args ...interface{}) {
|
func (l Logger) Infoln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -111,12 +129,13 @@ func (l Logger) Infoln(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "INFO",
|
Level: "INFO",
|
||||||
level: LInfo,
|
level: LInfo,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notice prints out logs on notice level
|
// Notice prints out logs on notice level
|
||||||
func (l Logger) Notice(args ...interface{}) {
|
func (l Logger) Notice(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -124,12 +143,13 @@ func (l Logger) Notice(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Notice
|
// Formatted print for Notice
|
||||||
func (l Logger) Noticef(format string, args ...interface{}) {
|
func (l Logger) Noticef(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -137,12 +157,13 @@ func (l Logger) Noticef(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notice prints out logs on notice level with newline
|
// Notice prints out logs on notice level with newline
|
||||||
func (l Logger) Noticeln(args ...interface{}) {
|
func (l Logger) Noticeln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -150,12 +171,13 @@ func (l Logger) Noticeln(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "NOTICE",
|
Level: "NOTICE",
|
||||||
level: LNotice,
|
level: LNotice,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Warn prints out logs on warn level
|
// Warn prints out logs on warn level
|
||||||
func (l Logger) Warn(args ...interface{}) {
|
func (l Logger) Warn(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -163,12 +185,13 @@ func (l Logger) Warn(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for Warn
|
// Formatted print for Warn
|
||||||
func (l Logger) Warnf(format string, args ...interface{}) {
|
func (l Logger) Warnf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -176,12 +199,13 @@ func (l Logger) Warnf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Warn prints out logs on warn level with a newline
|
// Warn prints out logs on warn level with a newline
|
||||||
func (l Logger) Warnln(args ...interface{}) {
|
func (l Logger) Warnln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -189,12 +213,13 @@ func (l Logger) Warnln(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "WARN",
|
Level: "WARN",
|
||||||
level: LWarn,
|
level: LWarn,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error prints out logs on error level
|
// Error prints out logs on error level
|
||||||
func (l Logger) Error(args ...interface{}) {
|
func (l Logger) Error(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -202,12 +227,13 @@ func (l Logger) Error(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for error
|
// Formatted print for error
|
||||||
func (l Logger) Errorf(format string, args ...interface{}) {
|
func (l Logger) Errorf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -215,12 +241,13 @@ func (l Logger) Errorf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error prints out logs on error level with a new line
|
// Error prints out logs on error level with a new line
|
||||||
func (l Logger) Errorln(args ...interface{}) {
|
func (l Logger) Errorln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -228,12 +255,13 @@ func (l Logger) Errorln(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "ERROR",
|
Level: "ERROR",
|
||||||
level: LError,
|
level: LError,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Panic prints out logs on panic level
|
// Panic prints out logs on panic level
|
||||||
func (l Logger) Panic(args ...interface{}) {
|
func (l Logger) Panic(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -241,6 +269,7 @@ func (l Logger) Panic(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) >= 0 {
|
if len(args) >= 0 {
|
||||||
@@ -256,7 +285,7 @@ func (l Logger) Panic(args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for panic
|
// Formatted print for panic
|
||||||
func (l Logger) Panicf(format string, args ...interface{}) {
|
func (l Logger) Panicf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -264,6 +293,7 @@ func (l Logger) Panicf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) >= 0 {
|
if len(args) >= 0 {
|
||||||
@@ -279,7 +309,7 @@ func (l Logger) Panicf(format string, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Panic prints out logs on panic level with a newline
|
// Panic prints out logs on panic level with a newline
|
||||||
func (l Logger) Panicln(args ...interface{}) {
|
func (l Logger) Panicln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -287,6 +317,7 @@ func (l Logger) Panicln(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "PANIC",
|
Level: "PANIC",
|
||||||
level: LPanic,
|
level: LPanic,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
if len(args) >= 0 {
|
if len(args) >= 0 {
|
||||||
@@ -302,7 +333,7 @@ func (l Logger) Panicln(args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fatal prints out logs on fatal level
|
// Fatal prints out logs on fatal level
|
||||||
func (l Logger) Fatal(args ...interface{}) {
|
func (l Logger) Fatal(args ...any) {
|
||||||
output := fmt.Sprint(args...)
|
output := fmt.Sprint(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -310,6 +341,7 @@ func (l Logger) Fatal(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
Flush()
|
Flush()
|
||||||
@@ -317,7 +349,7 @@ func (l Logger) Fatal(args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Formatted print for fatal
|
// Formatted print for fatal
|
||||||
func (l Logger) Fatalf(format string, args ...interface{}) {
|
func (l Logger) Fatalf(format string, args ...any) {
|
||||||
output := fmt.Sprintf(format, args...)
|
output := fmt.Sprintf(format, args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -325,6 +357,7 @@ func (l Logger) Fatalf(format string, args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
Flush()
|
Flush()
|
||||||
@@ -332,7 +365,7 @@ func (l Logger) Fatalf(format string, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fatal prints fatal level with a new line
|
// Fatal prints fatal level with a new line
|
||||||
func (l Logger) Fatalln(args ...interface{}) {
|
func (l Logger) Fatalln(args ...any) {
|
||||||
output := fmt.Sprintln(args...)
|
output := fmt.Sprintln(args...)
|
||||||
e := Entry{
|
e := Entry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
@@ -340,6 +373,7 @@ func (l Logger) Fatalln(args ...interface{}) {
|
|||||||
File: fileInfo(l.FileInfoDepth),
|
File: fileInfo(l.FileInfoDepth),
|
||||||
Level: "FATAL",
|
Level: "FATAL",
|
||||||
level: LFatal,
|
level: LFatal,
|
||||||
|
Namespace: l.Namespace,
|
||||||
}
|
}
|
||||||
createLog(e)
|
createLog(e)
|
||||||
Flush()
|
Flush()
|
||||||
@@ -347,16 +381,16 @@ func (l Logger) Fatalln(args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handles print to info
|
// Handles print to info
|
||||||
func (l Logger) Print(args ...interface{}) {
|
func (l Logger) Print(args ...any) {
|
||||||
l.Info(args...)
|
l.Info(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handles formatted print to info
|
// Handles formatted print to info
|
||||||
func (l Logger) Printf(format string, args ...interface{}) {
|
func (l Logger) Printf(format string, args ...any) {
|
||||||
l.Infof(format, args...)
|
l.Infof(format, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handles print to info with new line
|
// Handles print to info with new line
|
||||||
func (l Logger) Println(args ...interface{}) {
|
func (l Logger) Println(args ...any) {
|
||||||
l.Infoln(args...)
|
l.Infoln(args...)
|
||||||
}
|
}
|
||||||
|
|||||||
41
log/types.go
41
log/types.go
@@ -2,9 +2,6 @@ package log
|
|||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type LogWriter chan Entry
|
|
||||||
type Level int
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
LTrace Level = iota
|
LTrace Level = iota
|
||||||
LDebug
|
LDebug
|
||||||
@@ -16,20 +13,28 @@ const (
|
|||||||
LFatal
|
LFatal
|
||||||
)
|
)
|
||||||
|
|
||||||
type Client struct {
|
const DefaultNamespace = "default"
|
||||||
LogLevel Level `json:"level"`
|
|
||||||
writer LogWriter
|
|
||||||
initialized bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type Entry struct {
|
type (
|
||||||
Timestamp time.Time `json:"timestamp"`
|
LogWriter chan Entry
|
||||||
Output string `json:"output"`
|
Level int
|
||||||
File string `json:"file"`
|
|
||||||
Level string `json:"level"`
|
|
||||||
level Level
|
|
||||||
}
|
|
||||||
|
|
||||||
type Logger struct {
|
Client struct {
|
||||||
FileInfoDepth int
|
LogLevel Level `json:"level"`
|
||||||
}
|
Namespaces []string `json:"namespaces"` // Empty slice means all namespaces
|
||||||
|
writer LogWriter
|
||||||
|
initialized bool
|
||||||
|
}
|
||||||
|
Entry struct {
|
||||||
|
Timestamp time.Time `json:"timestamp"`
|
||||||
|
Output string `json:"output"`
|
||||||
|
File string `json:"file"`
|
||||||
|
Level string `json:"level"`
|
||||||
|
Namespace string `json:"namespace"`
|
||||||
|
level Level
|
||||||
|
}
|
||||||
|
Logger struct {
|
||||||
|
FileInfoDepth int
|
||||||
|
Namespace string
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|||||||
30
main.go
30
main.go
@@ -5,20 +5,33 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/taigrr/log-socket/browser"
|
"github.com/taigrr/log-socket/v2/browser"
|
||||||
logger "github.com/taigrr/log-socket/log"
|
logger "github.com/taigrr/log-socket/v2/log"
|
||||||
"github.com/taigrr/log-socket/ws"
|
"github.com/taigrr/log-socket/v2/ws"
|
||||||
)
|
)
|
||||||
|
|
||||||
var addr = flag.String("addr", "0.0.0.0:8080", "http service address")
|
var addr = flag.String("addr", "0.0.0.0:8080", "http service address")
|
||||||
|
|
||||||
func generateLogs() {
|
func generateLogs() {
|
||||||
|
// Create loggers for different namespaces
|
||||||
|
apiLogger := logger.NewLogger("api")
|
||||||
|
dbLogger := logger.NewLogger("database")
|
||||||
|
authLogger := logger.NewLogger("auth")
|
||||||
|
|
||||||
for {
|
for {
|
||||||
logger.Info("This is an info log!")
|
logger.Info("This is a default namespace log!")
|
||||||
logger.Trace("This is a trace log!")
|
apiLogger.Info("API request received")
|
||||||
logger.Debug("This is a debug log!")
|
apiLogger.Debug("Processing API call")
|
||||||
logger.Warn("This is a warn log!")
|
|
||||||
logger.Error("This is an error log!")
|
dbLogger.Info("Database query executed")
|
||||||
|
dbLogger.Warn("Slow query detected")
|
||||||
|
|
||||||
|
authLogger.Info("User authentication successful")
|
||||||
|
authLogger.Error("Failed login attempt detected")
|
||||||
|
|
||||||
|
logger.Trace("This is a trace log in default namespace!")
|
||||||
|
logger.Warn("This is a warning in default namespace!")
|
||||||
|
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -27,6 +40,7 @@ func main() {
|
|||||||
defer logger.Flush()
|
defer logger.Flush()
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
http.HandleFunc("/ws", ws.LogSocketHandler)
|
http.HandleFunc("/ws", ws.LogSocketHandler)
|
||||||
|
http.HandleFunc("/api/namespaces", ws.NamespacesHandler)
|
||||||
http.HandleFunc("/", browser.LogSocketViewHandler)
|
http.HandleFunc("/", browser.LogSocketViewHandler)
|
||||||
go generateLogs()
|
go generateLogs()
|
||||||
logger.Fatal(http.ListenAndServe(*addr, nil))
|
logger.Fatal(http.ListenAndServe(*addr, nil))
|
||||||
|
|||||||
17
ws/namespaces.go
Normal file
17
ws/namespaces.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package ws
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
logger "github.com/taigrr/log-socket/v2/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NamespacesHandler returns a JSON list of all namespaces that have been used
|
||||||
|
func NamespacesHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
namespaces := logger.GetNamespaces()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"namespaces": namespaces,
|
||||||
|
})
|
||||||
|
}
|
||||||
21
ws/server.go
21
ws/server.go
@@ -3,23 +3,34 @@ package ws
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
logger "github.com/taigrr/log-socket/log"
|
logger "github.com/taigrr/log-socket/v2/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
// var addr = flag.String("addr", "localhost:8080", "http service address")
|
|
||||||
|
|
||||||
var upgrader = websocket.Upgrader{} // use default options
|
var upgrader = websocket.Upgrader{} // use default options
|
||||||
|
|
||||||
|
func SetUpgrader(u websocket.Upgrader) {
|
||||||
|
upgrader = u
|
||||||
|
}
|
||||||
|
|
||||||
func LogSocketHandler(w http.ResponseWriter, r *http.Request) {
|
func LogSocketHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Get namespaces from query parameter, comma-separated
|
||||||
|
// Empty or missing means all namespaces
|
||||||
|
namespacesParam := r.URL.Query().Get("namespaces")
|
||||||
|
var namespaces []string
|
||||||
|
if 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)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer c.Close()
|
defer c.Close()
|
||||||
lc := logger.CreateClient()
|
lc := logger.CreateClient(namespaces...)
|
||||||
defer lc.Destroy()
|
defer lc.Destroy()
|
||||||
lc.SetLogLevel(logger.LTrace)
|
lc.SetLogLevel(logger.LTrace)
|
||||||
logger.Info("Websocket client attached.")
|
logger.Info("Websocket client attached.")
|
||||||
@@ -28,7 +39,7 @@ func LogSocketHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
logJSON, _ := json.Marshal(logEvent)
|
logJSON, _ := json.Marshal(logEvent)
|
||||||
err = c.WriteMessage(websocket.TextMessage, logJSON)
|
err = c.WriteMessage(websocket.TextMessage, logJSON)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("write:", err)
|
logger.Warn("write:", err)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user