-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.go
More file actions
94 lines (78 loc) · 1.76 KB
/
Copy pathfile.go
File metadata and controls
94 lines (78 loc) · 1.76 KB
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 logger
import (
"fmt"
"log"
"os"
"path"
"strings"
"github.com/mgutz/ansi"
)
var (
fileColors = map[int]string{
LevelError: "red",
LevelWarning: "yellow",
LevelNotice: "magenta",
LevelInfo: "blue",
LevelDebug: "cyan",
}
fileLabels map[int]string
)
type fileBackend struct {
logger *Logger
output *os.File
writer *log.Logger
level int
}
func newFileBackend(config FileConfig, logger *Logger) (backend, error) {
var (
output *os.File
useColors bool
err error
)
if config.Level == "" {
config.Level = defaultLevel
} else if _, ok := levelMap[config.Level]; !ok {
return nil, ErrInvalidLevel
}
if config.Path != "" && config.Path != "-" {
// Create parent folders if needed
dirPath, _ := path.Split(config.Path)
if dirPath != "" {
if err = os.MkdirAll(dirPath, 0755); err != nil {
return nil, err
}
}
// Open logging output file
if output, err = os.OpenFile(config.Path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err != nil {
return nil, fmt.Errorf("failed to open logging file: %s", err)
}
} else {
// Set logging output to stderr
output = os.Stderr
useColors = true
}
writer := log.New(output, "", log.LstdFlags|log.Lmicroseconds)
// Initialize labels
fileLabels = map[int]string{}
for name, level := range levelMap {
if useColors {
fileLabels[level] = ansi.Color(strings.ToUpper(name), fileColors[level])
} else {
fileLabels[level] = strings.ToUpper(name) + ":"
}
}
return &fileBackend{
logger: logger,
output: output,
writer: writer,
level: levelMap[config.Level],
}, nil
}
func (b fileBackend) Close() {
b.output.Close()
}
func (b fileBackend) Write(level int, mesg string) {
if level <= b.level {
b.writer.Printf("%s %s", fileLabels[level], mesg)
}
}