-
Notifications
You must be signed in to change notification settings - Fork 4
/
xlistener.go
71 lines (61 loc) · 1.43 KB
/
xlistener.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
package xlog
import (
"bufio"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// A Listener simple typed of io.Writer
type Listener io.WriteCloser
// W2FileListener use to output log to file.
type W2FileListener struct {
w *bufio.Writer
f *os.File
}
// Write is equivalent to os.File.Write.
func (l *W2FileListener) Write(p []byte) (n int, err error) {
return l.w.Write(p)
}
// Close is equivalent to os.File.Close.
func (l *W2FileListener) Close() error {
if l != nil && l.f != nil {
err := l.w.Flush()
if err2 := l.f.Close(); err2 != nil {
if err == nil {
err = err2
}
}
return err
}
return os.ErrInvalid
}
// NewW2FileListener creates a new W2FileListener.
// If filePath is empty, then will create file at appPath/Log/
func NewW2FileListener(filePath string) (*W2FileListener, error) {
if len(filePath) == 0 {
appDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return nil, err
}
baseName := filepath.Base(os.Args[0])
appName := strings.TrimSuffix(baseName, filepath.Ext(baseName))
timeStr := time.Now().Format("2006_01_02")
filePath = path.Join(appDir, "log", appName+"_"+timeStr+".log")
}
err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
if err != nil {
return nil, err
}
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
lis := &W2FileListener{
f: f,
w: bufio.NewWriter(f),
}
return lis, nil
}