-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_writer.go
94 lines (79 loc) · 1.73 KB
/
log_writer.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package internal
import (
"log"
"os"
"time"
"github.com/v2ray/v2ray-core/common/platform"
"github.com/v2ray/v2ray-core/common/signal"
)
type LogWriter interface {
Log(LogEntry)
Close()
}
type NoOpLogWriter struct {
}
func (this *NoOpLogWriter) Log(entry LogEntry) {
entry.Release()
}
func (this *NoOpLogWriter) Close() {
}
type StdOutLogWriter struct {
logger *log.Logger
cancel *signal.CancelSignal
}
func NewStdOutLogWriter() LogWriter {
return &StdOutLogWriter{
logger: log.New(os.Stdout, "", log.Ldate|log.Ltime),
cancel: signal.NewCloseSignal(),
}
}
func (this *StdOutLogWriter) Log(log LogEntry) {
this.logger.Print(log.String() + platform.LineSeparator())
log.Release()
}
func (this *StdOutLogWriter) Close() {
time.Sleep(500 * time.Millisecond)
}
type FileLogWriter struct {
queue chan string
logger *log.Logger
file *os.File
cancel *signal.CancelSignal
}
func (this *FileLogWriter) Log(log LogEntry) {
select {
case this.queue <- log.String():
default:
// We don't expect this to happen, but don't want to block main thread as well.
}
log.Release()
}
func (this *FileLogWriter) run() {
for {
entry, open := <-this.queue
if !open {
break
}
this.logger.Print(entry + platform.LineSeparator())
}
this.cancel.Done()
}
func (this *FileLogWriter) Close() {
close(this.queue)
<-this.cancel.WaitForDone()
this.file.Close()
}
func NewFileLogWriter(path string) (*FileLogWriter, error) {
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return nil, err
}
logger := &FileLogWriter{
queue: make(chan string, 16),
logger: log.New(file, "", log.Ldate|log.Ltime),
file: file,
cancel: signal.NewCloseSignal(),
}
go logger.run()
return logger, nil
}