81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package logger
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type EventLogger struct {
|
|
file *os.File
|
|
humanFile *os.File
|
|
mu sync.Mutex
|
|
}
|
|
|
|
func NewEventLogger() (*EventLogger, error) {
|
|
// Получаем пути к файлам
|
|
jsonPath, err := GetEventLogPath()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("ошибка получения пути для JSON логов: %w", err)
|
|
}
|
|
|
|
humanPath, err := GetEventHumanLogPath()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("ошибка получения пути для Human логов: %w", err)
|
|
}
|
|
|
|
// Открываем JSON файл
|
|
f, err := os.OpenFile(jsonPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("ошибка открытия JSON лога: %w", err)
|
|
}
|
|
|
|
// Открываем Human-readable файл
|
|
humanF, err := os.OpenFile(humanPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
f.Close()
|
|
return nil, fmt.Errorf("ошибка открытия Human лога: %w", 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
|
|
} |