forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
94 lines (78 loc) · 1.83 KB
/
log.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 logging
import (
"fmt"
"os"
"path/filepath"
"github.com/lxc/lxd/shared"
log "gopkg.in/inconshreveable/log15.v2"
)
// GetLogger returns a logger suitable for using as shared.Log.
func GetLogger(syslog string, logfile string, verbose bool, debug bool, customHandler log.Handler) (shared.Logger, error) {
Log := log.New()
var handlers []log.Handler
var syshandler log.Handler
// System specific handler
syshandler = getSystemHandler(syslog, debug)
if syshandler != nil {
handlers = append(handlers, syshandler)
}
// FileHandler
if logfile != "" {
if !pathExists(filepath.Dir(logfile)) {
return nil, fmt.Errorf("Log file path doesn't exist: %s", filepath.Dir(logfile))
}
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.Must.FileHandler(logfile, log.LogfmtFormat()),
),
)
} else {
handlers = append(handlers, log.Must.FileHandler(logfile, log.LogfmtFormat()))
}
}
// StderrHandler
if verbose || debug {
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.StderrHandler,
),
)
} else {
handlers = append(handlers, log.StderrHandler)
}
} else {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlWarn,
log.StderrHandler,
),
)
}
if customHandler != nil {
handlers = append(handlers, customHandler)
}
Log.SetHandler(log.MultiHandler(handlers...))
return Log, nil
}
func AddContext(logger shared.Logger, ctx log.Ctx) shared.Logger {
log15logger, ok := logger.(log.Logger)
if !ok {
logger.Error("couldn't downcast logger to add context", log.Ctx{"logger": log15logger, "ctx": ctx})
return logger
}
return log15logger.New(ctx)
}
func pathExists(name string) bool {
_, err := os.Lstat(name)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}