mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-02-03 04:50:52 +08:00
feat(config, usage): add usage-statistics-enabled option and dynamic toggling
- Introduced `usage-statistics-enabled` configuration to control in-memory usage aggregation. - Updated API to include handlers for managing `usage-statistics-enabled` and `logging-to-file` options. - Enhanced `watcher` to log changes to both configurations dynamically. - Updated documentation and examples to reflect new configuration options.
This commit is contained in:
@@ -7,13 +7,17 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
coreusage "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/usage"
|
||||
)
|
||||
|
||||
var statisticsEnabled atomic.Bool
|
||||
|
||||
func init() {
|
||||
statisticsEnabled.Store(true)
|
||||
coreusage.RegisterPlugin(NewLoggerPlugin())
|
||||
}
|
||||
|
||||
@@ -36,12 +40,21 @@ func NewLoggerPlugin() *LoggerPlugin { return &LoggerPlugin{stats: defaultReques
|
||||
// - ctx: The context for the usage record
|
||||
// - record: The usage record to aggregate
|
||||
func (p *LoggerPlugin) HandleUsage(ctx context.Context, record coreusage.Record) {
|
||||
if !statisticsEnabled.Load() {
|
||||
return
|
||||
}
|
||||
if p == nil || p.stats == nil {
|
||||
return
|
||||
}
|
||||
p.stats.Record(ctx, record)
|
||||
}
|
||||
|
||||
// SetStatisticsEnabled toggles whether in-memory statistics are recorded.
|
||||
func SetStatisticsEnabled(enabled bool) { statisticsEnabled.Store(enabled) }
|
||||
|
||||
// StatisticsEnabled reports the current recording state.
|
||||
func StatisticsEnabled() bool { return statisticsEnabled.Load() }
|
||||
|
||||
// RequestStatistics maintains aggregated request metrics in memory.
|
||||
type RequestStatistics struct {
|
||||
mu sync.RWMutex
|
||||
@@ -138,6 +151,9 @@ func (s *RequestStatistics) Record(ctx context.Context, record coreusage.Record)
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if !statisticsEnabled.Load() {
|
||||
return
|
||||
}
|
||||
timestamp := record.RequestedAt
|
||||
if timestamp.IsZero() {
|
||||
timestamp = time.Now()
|
||||
|
||||
Reference in New Issue
Block a user