forked from lalluviamola/web-blog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
114 lines (96 loc) · 2.33 KB
/
log.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// This code is in Public Domain. Take all the code you want, I'll just write more.
package main
// TODO: add an option to log to a file in the format:
// $time E: $msg
// $time N: $msg
// E: is for errors, N: is for notices
// format of $time is TBD (human readable is long, unix timestamp is short
// but not human-readable)
// TODO: gather all errors and email them periodically (e.g. every day) to myself
import (
"fmt"
"time"
)
type TimestampedMsg struct {
Time time.Time
Msg string
}
type CircularMessagesBuf struct {
Msgs []TimestampedMsg
pos int
full bool
}
func (m *TimestampedMsg) TimeStr() string {
return m.Time.Format("2006-01-02 15:04:05")
}
func (m *TimestampedMsg) TimeSinceStr() string {
return TimeSinceNowAsString(m.Time)
}
func NewCircularMessagesBuf(cap int) *CircularMessagesBuf {
return &CircularMessagesBuf{
Msgs: make([]TimestampedMsg, cap, cap),
pos: 0,
full: false,
}
}
func (b *CircularMessagesBuf) Add(s string) {
var msg = TimestampedMsg{time.Now(), s}
if b.pos == cap(b.Msgs) {
b.pos = 0
b.full = true
}
b.Msgs[b.pos] = msg
b.pos += 1
}
func (b *CircularMessagesBuf) GetOrdered() []*TimestampedMsg {
size := b.pos
if b.full {
size = cap(b.Msgs)
}
res := make([]*TimestampedMsg, size, size)
for i := 0; i < size; i++ {
p := b.pos - 1 - i
if p < 0 {
p = cap(b.Msgs) + p
}
res[i] = &b.Msgs[p]
}
return res
}
type ServerLogger struct {
Errors *CircularMessagesBuf
Notices *CircularMessagesBuf
UseStdout bool
}
func NewServerLogger(errorsMax, noticesMax int, useStdout bool) *ServerLogger {
l := &ServerLogger{
Errors: NewCircularMessagesBuf(errorsMax),
Notices: NewCircularMessagesBuf(noticesMax),
UseStdout: useStdout,
}
return l
}
func (l *ServerLogger) Error(s string) {
l.Errors.Add(s)
fmt.Printf("Error: %s\n", s)
}
func (l *ServerLogger) Errorf(format string, v ...interface{}) {
s := fmt.Sprintf(format, v...)
l.Errors.Add(s)
fmt.Printf("Error: %s\n", s)
}
func (l *ServerLogger) Notice(s string) {
l.Notices.Add(s)
fmt.Printf("%s\n", s)
}
func (l *ServerLogger) Noticef(format string, v ...interface{}) {
s := fmt.Sprintf(format, v...)
l.Notices.Add(s)
fmt.Printf("%s\n", s)
}
func (l *ServerLogger) GetErrors() []*TimestampedMsg {
return l.Errors.GetOrdered()
}
func (l *ServerLogger) GetNotices() []*TimestampedMsg {
return l.Notices.GetOrdered()
}