/
log.go
182 lines (160 loc) · 4.73 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
// Copyright 2019 The OpenSDS Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package obs
import (
"fmt"
"io"
"log"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/go-ini/ini"
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
)
type LogFormatter struct {
TimestampFormat string
LogFormat string
}
const (
debugLevel = "debug"
infoLevel = "info"
warnLevel = "warn"
errorLevel = "error"
path = "path"
level = "level"
format = "format"
defaultLogPath = "/var/log/multi-cloud"
defaultLogLevel = "info"
unknownHost = "unknownhost"
unknownUser = "unknownuser"
configFileName = "/etc/multi-cloud/multi-cloud.conf"
defaultLogFormat = "[%time%] [%level%] [%filename%] [%funcName%():%lineNo%] [PID:%process%] %message%"
defaultTimestampFormat = time.RFC3339
logSection = "log"
tenMb = 10
threeMonth = 100
)
func InitLogs() {
path, level, format := readConfigurationFile()
configureLogModule(path, level, format)
}
func configureLogModule(path, level, format string) {
configureWriter(path, format)
configureLevel(level)
}
func configureWriter(path, format string) {
logrus.SetFormatter(&LogFormatter{
TimestampFormat: defaultTimestampFormat,
LogFormat: format + "\n",
})
fileWriter := &lumberjack.Logger{
Filename: filepath.Join(path, logName()),
MaxSize: tenMb,
MaxAge: threeMonth,
Compress: true,
}
multiWriter := io.MultiWriter(os.Stdout, fileWriter)
logrus.SetOutput(multiWriter)
}
func configureLevel(level string) {
switch level {
case debugLevel:
logrus.SetLevel(logrus.DebugLevel)
case infoLevel:
logrus.SetLevel(logrus.InfoLevel)
case warnLevel:
logrus.SetLevel(logrus.WarnLevel)
case errorLevel:
logrus.SetLevel(logrus.ErrorLevel)
}
logrus.SetReportCaller(true)
}
func logName() (name string) {
name = fmt.Sprintf("%s.%s.%s.log",
filepath.Base(os.Args[0]),
hostName(),
userName())
return name
}
func shortHostname(hostname string) string {
if i := strings.Index(hostname, "."); i >= 0 {
return hostname[:i]
}
return hostname
}
func hostName() string {
host := unknownHost
h, err := os.Hostname()
if err == nil {
host = shortHostname(h)
}
return host
}
func userName() string {
userName := unknownUser
current, err := user.Current()
if err == nil {
userName = current.Username
}
// Sanitize userName since it may contain filepath separators on Windows.
userName = strings.Replace(userName, `\`, "_", -1)
return userName
}
func readConfigurationFile() (cfgPath, cfgLevel, cfgFormat string) {
cfgPath = defaultLogPath
cfgLevel = defaultLogLevel
cfgFormat = defaultLogFormat
cfg, err := ini.Load(configFileName)
if err != nil {
log.Println("Failed to open config file")
return cfgPath, cfgLevel, cfgFormat
}
if cfg.Section(logSection).HasKey(path) {
cfgPath = cfg.Section(logSection).Key(path).String()
}
if cfg.Section(logSection).HasKey(level) {
cfgLevel = strings.ToLower(cfg.Section(logSection).Key(level).String())
}
if cfg.Section(logSection).HasKey(format) {
cfgFormat = cfg.Section(logSection).Key(format).String()
}
return cfgPath, cfgLevel, cfgFormat
}
func (f *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
output := f.LogFormat
if output == "" {
output = defaultLogFormat
}
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
output = strings.Replace(output, "%time%", entry.Time.Format(timestampFormat), 1)
output = strings.Replace(output, "%message%", entry.Message, 1)
level := strings.ToUpper(entry.Level.String())
output = strings.Replace(output, "%level%", level, 1)
output = strings.Replace(output, "%process%", strconv.Itoa(os.Getpid()), 1)
output = strings.Replace(output, "%filename%", entry.Caller.File, 1)
output = strings.Replace(output, "%lineNo%", strconv.Itoa(entry.Caller.Line), 1)
funcName := entry.Caller.Function
if strings.Contains(funcName, "/") {
funcName = string([]byte(funcName)[strings.LastIndex(funcName, "/")+1:])
}
output = strings.Replace(output, "%funcName%", funcName, 1)
return []byte(output), nil
}