79 lines
1.5 KiB
Go
79 lines
1.5 KiB
Go
package logger
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type EventLogger struct {
|
|
file *os.File
|
|
humanFile *os.File
|
|
mu sync.Mutex
|
|
}
|
|
|
|
func NewEventLogger(path string) (*EventLogger, error) {
|
|
// Создаём директорию для логов
|
|
dir := filepath.Dir(path)
|
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// JSON файл для событий
|
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Human-readable файл для событий
|
|
humanPath := filepath.Join(dir, "events_human.log")
|
|
humanF, err := os.OpenFile(humanPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
f.Close()
|
|
return nil, err
|
|
}
|
|
|
|
return &EventLogger{
|
|
file: f,
|
|
humanFile: humanF,
|
|
}, nil
|
|
}
|
|
|
|
func (l *EventLogger) Event(name string) {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
|
|
now := time.Now()
|
|
|
|
// JSON формат (для машин)
|
|
ev := struct {
|
|
Timestamp int64 `json:"ts"`
|
|
Time string `json:"time"`
|
|
Event string `json:"event"`
|
|
}{
|
|
Timestamp: now.Unix(),
|
|
Time: now.Format("2006-01-02 15:04:05"),
|
|
Event: name,
|
|
}
|
|
|
|
data, _ := json.Marshal(ev)
|
|
data = append(data, '\n')
|
|
l.file.Write(data)
|
|
|
|
// Human-readable формат
|
|
humanLine := fmt.Sprintf("[%s] EVENT: %s\n", now.Format("2006-01-02 15:04:05.000"), name)
|
|
l.humanFile.WriteString(humanLine)
|
|
|
|
l.file.Sync()
|
|
l.humanFile.Sync()
|
|
}
|
|
|
|
func (l *EventLogger) Close() error {
|
|
l.file.Close()
|
|
l.humanFile.Close()
|
|
return nil
|
|
}
|