-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
107 lines (92 loc) · 1.92 KB
/
logger.go
File metadata and controls
107 lines (92 loc) · 1.92 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
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
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
const (
LOGLEVEL_DEBUG = 0
LOGLEVEL_INFO = 1
LOGLEVEL_WARN = 2
LOGLEVEL_ERROR = 3
LOGLEVEL_FATAL = 4
LOGLEVEL_DEV_DEBUG_VERBOSE = -1
)
var (
logFile *os.File
currentLogLevel int
hostname string
username string
processName string
pid int
)
func InitLogger(level int) {
currentLogLevel = level
hostname, _ = os.Hostname()
username = os.Getenv("USERNAME")
pid = os.Getpid()
processName = filepath.Base(os.Args[0])
}
func SetLogToFile(filePath string) {
if logFile != nil {
logFile.Close()
}
var err error
logFile, err = os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Printf("Error opening log file: %v\n", err)
logFile = nil
}
}
func CloseLogger() {
if logFile != nil {
fmt.Printf("Closing log file.\n")
logFile.Sync()
logFile.Close()
logFile = nil
}
}
func CleanData(message string) string {
cleanedData := strings.ReplaceAll(message, "\n", "\\n")
cleanedData = strings.ReplaceAll(cleanedData, "\r", "\\r")
return cleanedData
}
func logMessage(level int, message string) {
if level < currentLogLevel {
return
}
logPrefix := ""
switch level {
case LOGLEVEL_DEBUG:
logPrefix = "DEBUG"
case LOGLEVEL_INFO:
logPrefix = "INFO"
case LOGLEVEL_WARN:
logPrefix = "WARN"
case LOGLEVEL_ERROR:
logPrefix = "ERROR"
case LOGLEVEL_FATAL:
logPrefix = "FATAL"
case LOGLEVEL_DEV_DEBUG_VERBOSE:
logPrefix = "DEV_DEBUG_VERBOSE"
}
logEntry := fmt.Sprintf("[%s] [%s] Hostname: %s - Username: %s - ProcessName: %s - PID: %d - Message: %s\n",
time.Now().Format("2006-01-02 15:04:05.000000"),
logPrefix,
hostname,
username,
processName,
pid,
CleanData(message),
)
if logFile != nil {
_, err := logFile.WriteString(logEntry)
if err != nil {
fmt.Printf("Error writing to log file: %v\n", err)
}
} else {
fmt.Print(logEntry)
}
}