-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
60 lines (50 loc) · 1.14 KB
/
logger.go
File metadata and controls
60 lines (50 loc) · 1.14 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
package devlogger
import (
"fmt"
"log"
"os"
"time"
)
type Logger struct {
toFile bool
filePath string
file *os.File
}
// Constructor
func NewLogger(toFile bool, filePath string) *Logger {
var file *os.File
var err error
if toFile {
file, err = os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("Failed to open log file: %v", err)
}
}
return &Logger{
toFile: toFile,
filePath: filePath,
file: file,
}
}
// Helper function
func (l *Logger) log(level, message string) {
timestamp := time.Now().Format("2006-01-02 15:04:05")
formatted := fmt.Sprintf("[%s] %s: %s", timestamp, level, message)
// Print to console
fmt.Println(formatted)
// Write to file if enabled
if l.toFile && l.file != nil {
_, err := l.file.WriteString(formatted + "\n")
if err != nil {
log.Printf("Failed to write log: %v", err)
}
}
}
func (l *Logger) Info(msg string) { l.log("INFO", msg) }
func (l *Logger) Warning(msg string) { l.log("WARNING", msg) }
func (l *Logger) Error(msg string) { l.log("ERROR", msg) }
func (l *Logger) Close() {
if l.file != nil {
l.file.Close()
}
}