forked from AliyunContainerService/pouch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonfile.go
60 lines (49 loc) · 1.03 KB
/
jsonfile.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
package jsonfile
import (
"os"
"sync"
"github.com/alibaba/pouch/daemon/logger"
)
// JSONLogFile is uses to log the container's stdout and stderr.
type JSONLogFile struct {
mu sync.Mutex
f *os.File
perms os.FileMode
closed bool
}
// NewJSONLogFile returns new JSONLogFile instance.
func NewJSONLogFile(logPath string, perms os.FileMode) (*JSONLogFile, error) {
f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, perms)
if err != nil {
return nil, err
}
return &JSONLogFile{
f: f,
perms: perms,
closed: false,
}, nil
}
// WriteLogMessage will write the LogMessage into the file.
func (lf *JSONLogFile) WriteLogMessage(msg *logger.LogMessage) error {
b, err := marshal(msg)
if err != nil {
return err
}
lf.mu.Lock()
defer lf.mu.Unlock()
_, err = lf.f.Write(b)
return err
}
// Close closes the file.
func (lf *JSONLogFile) Close() error {
lf.mu.Lock()
defer lf.mu.Unlock()
if lf.closed {
return nil
}
if err := lf.f.Close(); err != nil {
return err
}
lf.closed = true
return nil
}