Passed
Push — main ( f6597a...58b626 )
by Yume
01:31 queued 12s
created

misc.newRollingFile   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
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