Files
s41r4j 0f03d49514
CI / contracts (push) Canceled after 0s
Website / deploy (push) Canceled after 0s
CI / test (macos-latest) (push) Canceled after 0s
CI / test (ubuntu-24.04) (push) Canceled after 0s
CI / test (ubuntu-24.04-arm) (push) Canceled after 0s
CI / test (windows-latest) (push) Canceled after 0s
CI / Compact real-tool fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Compact real-tool fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / Code analysis fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Code analysis fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / Web engine fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Web engine fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / Chromium operation fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Chromium operation fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
CI / operation-readiness (push) Canceled after 0s
CI / Supply chain fixtures (ubuntu-24.04) (push) Canceled after 0s
CI / Supply chain fixtures (ubuntu-24.04-arm) (push) Canceled after 0s
Initial commit
2026-11-01 09:14:18 +05:30

58 lines
1.1 KiB
Go

package telemetry
import (
"bufio"
"context"
"encoding/json"
"errors"
"os"
"sync"
"github.com/s41r4j/cybot/pkg/schema"
)
type Logger struct {
path string
mu sync.Mutex
}
func New(path string) *Logger { return &Logger{path: path} }
func (l *Logger) Write(_ context.Context, e schema.AuditEvent) error {
l.mu.Lock()
defer l.mu.Unlock()
f, err := os.OpenFile(l.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(e)
}
func (l *Logger) Read(limit int) ([]schema.AuditEvent, error) {
l.mu.Lock()
defer l.mu.Unlock()
f, err := os.Open(l.path)
if errors.Is(err, os.ErrNotExist) {
return []schema.AuditEvent{}, nil
}
if err != nil {
return nil, err
}
defer f.Close()
all := []schema.AuditEvent{}
s := bufio.NewScanner(f)
s.Buffer(make([]byte, 64*1024), 1024*1024)
for s.Scan() {
var e schema.AuditEvent
if json.Unmarshal(s.Bytes(), &e) == nil {
all = append(all, e)
}
}
if err = s.Err(); err != nil {
return nil, err
}
if limit > 0 && len(all) > limit {
all = all[len(all)-limit:]
}
return all, nil
}