Files
cc-connect/daemon/logrotate.go
T
chenhg5andClaude Opus 4.6 9a291eb0c3 feat: add daemon mode for running as background service
Add support for running cc-connect as a daemon managed by OS init system:
- Linux: systemd user service
- macOS: launchd LaunchAgent

New CLI commands:
- cc-connect daemon install/uninstall
- cc-connect daemon start/stop/restart/status
- cc-connect daemon logs [-f] [-n N] [--log-file PATH]

Features:
- Auto log rotation with configurable max size
- Cross-platform support (systemd/launchd)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 00:18:55 +08:00

77 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package daemon
import (
"os"
"path/filepath"
"sync"
)
// RotatingWriter is a thread-safe io.Writer that appends to a log file
// and rotates it when the file exceeds maxSize. One backup (.1) is kept,
// so the maximum disk usage is ≈ 2 × maxSize.
type RotatingWriter struct {
mu sync.Mutex
file *os.File
path string
maxSize int64
curSize int64
}
func NewRotatingWriter(path string, maxSize int64) (*RotatingWriter, error) {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return nil, err
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return nil, err
}
info, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
return &RotatingWriter{
file: f,
path: path,
maxSize: maxSize,
curSize: info.Size(),
}, nil
}
func (w *RotatingWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
n, err := w.file.Write(p)
w.curSize += int64(n)
if w.curSize > w.maxSize {
w.rotate()
}
return n, err
}
func (w *RotatingWriter) rotate() {
w.file.Close()
backup := w.path + ".1"
os.Remove(backup)
os.Rename(w.path, backup)
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
f, _ = os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
}
w.file = f
w.curSize = 0
}
func (w *RotatingWriter) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
if w.file != nil {
return w.file.Close()
}
return nil
}