|
1
|
|
|
package misc |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"io" |
|
5
|
|
|
"path" |
|
6
|
|
|
"sync" |
|
7
|
|
|
|
|
8
|
|
|
"github.com/memnix/memnix-rest/config" |
|
9
|
|
|
"github.com/rs/zerolog/log" |
|
10
|
|
|
"gopkg.in/natefinch/lumberjack.v2" |
|
11
|
|
|
) |
|
12
|
|
|
|
|
13
|
|
|
var logsChan = make(chan string, config.LogChannelSize) // buffered channel |
|
14
|
|
|
|
|
15
|
|
|
// LogWriter is a custom writer for logs to be used |
|
16
|
|
|
// It implements the io.Writer interface |
|
17
|
|
|
type LogWriter struct{} |
|
18
|
|
|
|
|
19
|
|
|
// Write is the implementation of the io.Writer interface |
|
20
|
|
|
// It writes the log to the logsChan channel to be processed by the LogWorker |
|
21
|
|
|
func (e LogWriter) Write(p []byte) (int, error) { |
|
22
|
|
|
logsChan <- string(p) // write to channel |
|
23
|
|
|
return 0, nil |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
// LogWorker is the worker that will process the logsChan channel |
|
27
|
|
|
func LogWorker(logs <-chan string, wg *sync.WaitGroup) { |
|
28
|
|
|
defer wg.Done() // signal that we are done |
|
29
|
|
|
// Infinite loop |
|
30
|
|
|
for { |
|
31
|
|
|
logContent := <-logs // read from channel |
|
32
|
|
|
_, err := newRollingFile().Write([]byte(logContent)) // write to file |
|
33
|
|
|
if err != nil { |
|
34
|
|
|
// log error |
|
35
|
|
|
log.Error().Err(err).Msg("Error writing to file") |
|
36
|
|
|
continue |
|
37
|
|
|
} |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
// CreateLogger creates a new LogWorker in a goroutine and waits for it to finish |
|
42
|
|
|
func CreateLogger() { |
|
43
|
|
|
var wg sync.WaitGroup // wait group |
|
44
|
|
|
wg.Add(1) // add one to wait group |
|
45
|
|
|
go LogWorker(logsChan, &wg) // start LogWorker in a goroutine |
|
46
|
|
|
wg.Wait() // wait for LogWorker to finish |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
// newRollingFile creates a new rolling file |
|
50
|
|
|
// It uses the lumberjack package to create a rolling file |
|
51
|
|
|
// It returns an io.Writer interface |
|
52
|
|
|
func newRollingFile() io.Writer { |
|
53
|
|
|
return &lumberjack.Logger{ |
|
54
|
|
|
Filename: path.Join("./logs", "api.log"), // file path |
|
55
|
|
|
MaxBackups: config.MaxBackupLogFiles, // files |
|
56
|
|
|
MaxSize: config.MaxSizeLogFiles, // megabytes |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|