-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlog.go
More file actions
81 lines (71 loc) · 1.96 KB
/
log.go
File metadata and controls
81 lines (71 loc) · 1.96 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
// SPDX-FileCopyrightText: 2017-2018 SAP SE or an SAP affiliate company
// SPDX-License-Identifier: Apache-2.0
// Package logg provides some convenience functions on top of the "log" package
// from the stdlib. It always uses the stdlib's standard logger.
//
// The functions in this package work like log.Println() or like log.Printf()
// depending on whether arguments are passed after the message string:
//
// import (
// "log"
// "github.com/sapcc/go-bits/logg"
// )
//
// //The following two are equivalent:
// logg.Info("starting up")
// std_log.Println("INFO: starting up")
//
// //The following two are equivalent:
// logg.Info("listening on port %d", port)
// std_log.Printf("INFO: listening on port %d\n", port)
package logg
import (
stdlog "log"
"os"
"strings"
"sync"
)
var (
// ShowDebug can be set to true to enable the display of debug logs.
ShowDebug = false
log = stdlog.New(stdlog.Writer(), stdlog.Prefix(), stdlog.Flags())
mu sync.Mutex
)
// SetLogger allows to define custom logger
func SetLogger(l *stdlog.Logger) {
mu.Lock()
defer mu.Unlock()
log = l
}
// Fatal logs a fatal error and terminates the program.
func Fatal(msg string, args ...any) {
doLog("FATAL: "+msg, args)
os.Exit(1)
}
// Error logs a non-fatal error.
func Error(msg string, args ...any) {
doLog("ERROR: "+msg, args)
}
// Info logs an informational message.
func Info(msg string, args ...any) {
doLog("INFO: "+msg, args)
}
// Debug logs a debug message if debug logging is enabled.
func Debug(msg string, args ...any) {
if ShowDebug {
doLog("DEBUG: "+msg, args)
}
}
// Other logs a message with a custom log level.
func Other(level, msg string, args ...any) {
doLog(level+": "+msg, args)
}
func doLog(msg string, args []any) {
msg = strings.TrimSpace(msg) // most importantly, skip trailing '\n'
msg = strings.ReplaceAll(msg, "\n", "\\n") // avoid multiline log messages
if len(args) > 0 {
log.Printf(msg+"\n", args...)
} else {
log.Println(msg)
}
}