forked from statping/statping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
216 lines (195 loc) · 5.35 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Statping
// Copyright (C) 2018. Hunter Long and the project contributors
// Written by Hunter Long <[email protected]> and the project contributors
//
// https://github.com/hunterlong/statping
//
// The licenses for most software and other practical works are designed
// to take away your freedom to share and change the works. By contrast,
// the GNU General Public License is intended to guarantee your freedom to
// share and change all versions of a program--to make sure it remains free
// software for all its users.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package utils
import (
"fmt"
"github.com/fatih/structs"
"github.com/hunterlong/statping/types"
Logger "github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
"io"
"os"
"reflect"
"strings"
"sync"
"time"
)
var (
Log = Logger.StandardLogger()
ljLogger *lumberjack.Logger
LastLines []*logRow
LockLines sync.Mutex
VerboseMode int
)
const logFilePath = "/logs/statping.log"
type hook struct {
Entries []Logger.Entry
mu sync.RWMutex
}
func (t *hook) Fire(e *Logger.Entry) error {
pushLastLine(e.Message)
return nil
}
func (t *hook) Levels() []Logger.Level {
return Logger.AllLevels
}
// ToFields accepts any amount of interfaces to create a new mapping for log.Fields. You will need to
// turn on verbose mode by starting Statping with "-v". This function will convert a struct of to the
// base struct name, and each field into it's own mapping, for example:
// type "*types.Service", on string field "Name" converts to "service_name=value". There is also an
// additional field called "_pointer" that will return the pointer hex value.
func ToFields(d ...interface{}) map[string]interface{} {
if !Log.IsLevelEnabled(Logger.DebugLevel) {
return nil
}
fieldKey := make(map[string]interface{})
for _, v := range d {
spl := strings.Split(fmt.Sprintf("%T", v), ".")
trueType := spl[len(spl)-1]
if !structs.IsStruct(v) {
continue
}
for _, f := range structs.Fields(v) {
if f.IsExported() && !f.IsZero() && f.Kind() != reflect.Ptr && f.Kind() != reflect.Slice && f.Kind() != reflect.Chan {
field := strings.ToLower(trueType + "_" + f.Name())
fieldKey[field] = replaceVal(f.Value())
}
}
fieldKey[strings.ToLower(trueType+"_pointer")] = fmt.Sprintf("%p", v)
}
return fieldKey
}
// replaceVal accepts an interface to be converted into human readable type
func replaceVal(d interface{}) interface{} {
switch v := d.(type) {
case types.NullBool:
return v.Bool
case types.NullString:
return v.String
case types.NullFloat64:
return v.Float64
case types.NullInt64:
return v.Int64
case string:
if len(v) > 500 {
return v[:500] + "... (truncated in logs)"
}
return v
case time.Time:
return v.String()
case time.Duration:
return v.String()
default:
return d
}
}
// createLog will create the '/logs' directory based on a directory
func createLog(dir string) error {
if !FolderExists(dir + "/logs") {
CreateDirectory(dir + "/logs")
}
return nil
}
// InitLogs will create the '/logs' directory and creates a file '/logs/statup.log' for application logging
func InitLogs() error {
if err := createLog(Directory); err != nil {
return err
}
ljLogger = &lumberjack.Logger{
Filename: Directory + logFilePath,
MaxSize: 16,
MaxBackups: 5,
MaxAge: 28,
}
mw := io.MultiWriter(os.Stdout, ljLogger)
Log.SetOutput(mw)
Log.SetFormatter(&Logger.TextFormatter{
ForceColors: true,
DisableColors: false,
})
checkVerboseMode()
LastLines = make([]*logRow, 0)
return nil
}
// checkVerboseMode will reset the Logging verbose setting. You can set
// the verbose level with "-v 3" or by setting VERBOSE=3 environment variable.
// statping -v 1 (only Warnings)
// statping -v 2 (Info and Warnings, default)
// statping -v 3 (Info, Warnings and Debug)
// statping -v 4 (Info, Warnings, Debug and Traces (SQL queries))
func checkVerboseMode() {
switch VerboseMode {
case 1:
Log.SetLevel(Logger.WarnLevel)
case 2:
Log.SetLevel(Logger.InfoLevel)
case 3:
Log.SetLevel(Logger.DebugLevel)
case 4:
Log.SetReportCaller(true)
Log.SetLevel(Logger.TraceLevel)
default:
Log.SetLevel(Logger.InfoLevel)
}
Log.Debugf("logging running in %v mode", Log.GetLevel().String())
}
// CloseLogs will close the log file correctly on shutdown
func CloseLogs() {
ljLogger.Rotate()
Log.Writer().Close()
ljLogger.Close()
}
func pushLastLine(line interface{}) {
LockLines.Lock()
defer LockLines.Unlock()
LastLines = append(LastLines, newLogRow(line))
// We want to store max 1000 lines in memory (for /logs page).
for len(LastLines) > 1000 {
LastLines = LastLines[1:]
}
}
// GetLastLine returns 1 line for a recent log entry
func GetLastLine() *logRow {
LockLines.Lock()
defer LockLines.Unlock()
if len(LastLines) > 0 {
return LastLines[len(LastLines)-1]
}
return nil
}
type logRow struct {
Date time.Time
Line interface{}
}
func newLogRow(line interface{}) (lgRow *logRow) {
lgRow = new(logRow)
lgRow.Date = time.Now()
lgRow.Line = line
return
}
func (o *logRow) lineAsString() string {
switch v := o.Line.(type) {
case string:
return v
case error:
return v.Error()
case []byte:
return string(v)
}
return ""
}
func (o *logRow) FormatForHtml() string {
return fmt.Sprintf("%s: %s", o.Date.Format("2006-01-02 15:04:05"), o.lineAsString())
}