-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
100 lines (75 loc) · 1.65 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"bufio"
"errors"
"fmt"
"os"
"time"
)
const log_path = "logs";
type LogNode struct {
log string;
next *LogNode;
}
type LogQueue struct {
len int;
head *LogNode;
tail *LogNode;
}
func enqueue_log(queue *LogQueue, mes string) {
var newLog *LogNode = &LogNode {
log: mes,
next: nil,
}
if queue.len == 0 {
queue.head = newLog;
} else {
queue.tail.next = newLog;
}
queue.tail = newLog;
queue.len++;
}
func dequeue_log(queue *LogQueue) (string, error) {
if queue.len < 1 {
return "", errors.New("LogQueue is empty!\n");
}
var log string = queue.head.log;
if queue.len == 1 {
queue.head = nil;
queue.tail = nil;
} else {
queue.head = queue.head.next;
}
queue.len--;
return log, nil;
}
func Log(mes string) {
f_in, err := os.Open(log_path);
if err != nil {
os.Stderr.WriteString(err.Error());
}
defer f_in.Close();
var queue LogQueue = LogQueue {
len: 0,
head: nil,
tail: nil,
};
scanner := bufio.NewScanner(f_in);
for scanner.Scan() {
enqueue_log(&queue, scanner.Text());
}
f_out, err := os.OpenFile(log_path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm);
if err != nil {
os.Stderr.WriteString(err.Error());
}
defer f_out.Close()
message := fmt.Sprintf("%s - %s\n", time.Now().Format("2006-01-02 15:04:05"), mes);
f_out.WriteString(message);
for {
log, err := dequeue_log(&queue);
if err != nil {
break;
}
f_out.WriteString(log + "\n");
}
}