-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
60 lines (50 loc) · 1020 Bytes
/
Copy pathlogger.go
File metadata and controls
60 lines (50 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package backend
import (
"fmt"
"os"
"sync"
)
type Logger struct {
mu sync.Mutex
file *os.File
}
func NewLogger(path string) (*Logger, error) {
if err := ensureDir(filepathDir(path)); err != nil {
return nil, err
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return nil, err
}
return &Logger{file: file}, nil
}
func (l *Logger) Close() error {
if l == nil || l.file == nil {
return nil
}
return l.file.Close()
}
func (l *Logger) Write(entry LogEntry) error {
if l == nil || l.file == nil {
return nil
}
l.mu.Lock()
defer l.mu.Unlock()
_, err := fmt.Fprintf(l.file, "%s | %s | %s | %s\n", entry.Timestamp, entry.Kind, entry.Level, entry.Message)
return err
}
func filepathDir(path string) string {
last := len(path) - 1
for last >= 0 && (path[last] == '\\' || path[last] == '/') {
last--
}
if last < 0 {
return ""
}
for i := last; i >= 0; i-- {
if path[i] == '\\' || path[i] == '/' {
return path[:i]
}
}
return ""
}