-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
82 lines (69 loc) · 2.23 KB
/
logger.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
package logger
import (
"fmt"
"os"
"time"
"github.com/fatih/color"
)
// base The base formatted string to be printed by the Logger.
// magenta A magenta colour utilised for "DEBUG" level logs.
// cyan A cyan colour utilised for standard output to the Logger.
// green A green colour utilised for "INFO" level logs.
// yellow A yellow colour utilised for "WARN" level logs.
// red A red colour utilised for "ERROR" level logs.
// boldRed A bold red colour utilised for "FATAL" level logs.
var (
base = "[%s] %s [%s] - %s\r\n"
magenta = color.New(color.FgMagenta).SprintFunc()
cyan = color.New(color.FgCyan).SprintFunc()
green = color.New(color.FgGreen).SprintFunc()
yellow = color.New(color.FgYellow).SprintFunc()
red = color.New(color.FgRed).SprintFunc()
boldRed = color.New(color.FgHiRed).Add(color.Bold).SprintFunc()
)
// LoggerInterface
// A structure containing the Prefix or name of the service that logs are written for.
type LoggerInterface struct {
Prefix string
}
// isNullOrEmptyString
// Returns a boolean value indicating if a string is either empty or null.
func isNullOrEmptyString(str string) bool {
if str == "" || len(str) <= 0 {
return true
}
return false
}
// formatSeverity
// Private method to convert the provided severity string to its corresponding colour for printing.
func formatSeverity(severity string) string {
var formattedSeverity string
switch severity {
case "DEBUG":
formattedSeverity = magenta(severity)
case "INFO":
formattedSeverity = green(severity)
case "WARN":
formattedSeverity = yellow(severity)
case "ERROR":
formattedSeverity = red(severity)
case "FATAL":
formattedSeverity = boldRed(severity)
}
return formattedSeverity
}
// LogMessage
// Structure method to print a log message provided both a message and severity.
func (l *LoggerInterface) LogMessage(message, severity string) {
if isNullOrEmptyString(message) {
l.LogMessage("No message string passed to logger interface.", "ERROR")
}
if isNullOrEmptyString(severity) {
l.LogMessage("No severity string passed to logger interface.", "ERROR")
}
logTime := time.Now().Format("2006-01-02 15:04:05")
fmt.Printf(base, logTime, formatSeverity(severity), l.Prefix, cyan(message))
if severity == "FATAL" {
os.Exit(1)
}
}