Files
Prism/internal/log/collector.go
T
renjue 59d1087cc9
CI / test (push) Failing after 1m46s
CI / docker (push) Has been skipped
feat: Prism HTTP/SOCKS5 代理网关及管理台
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-23 15:08:50 +08:00

68 lines
1.2 KiB
Go

package applog
import (
"context"
"sync"
"time"
"github.com/prism/proxy/internal/store"
)
type Entry struct {
Level string `json:"level"`
Source string `json:"source"`
Message string `json:"message"`
CreatedAt time.Time `json:"created_at"`
}
type Collector struct {
mu sync.RWMutex
ring []Entry
cap int
store *store.Store
persist bool
}
func NewCollector(s *store.Store, capacity int, persist bool) *Collector {
return &Collector{
ring: make([]Entry, 0, capacity),
cap: capacity,
store: s,
persist: persist,
}
}
func (c *Collector) Add(level, source, message string) {
e := Entry{
Level: level,
Source: source,
Message: message,
CreatedAt: time.Now(),
}
c.mu.Lock()
if len(c.ring) >= c.cap {
c.ring = c.ring[1:]
}
c.ring = append(c.ring, e)
c.mu.Unlock()
if c.persist && c.store != nil {
_ = c.store.AddRequestLog(context.Background(), level, source, message)
}
}
func (c *Collector) List(limit int) []Entry {
c.mu.RLock()
defer c.mu.RUnlock()
if limit <= 0 || limit > len(c.ring) {
limit = len(c.ring)
}
start := len(c.ring) - limit
if start < 0 {
start = 0
}
out := make([]Entry, limit)
copy(out, c.ring[start:])
return out
}