Passed
Pull Request — main (#119)
by Yume
01:34
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
	"sync"
5
	"time"
6
7
	"github.com/influxdata/influxdb-client-go/v2/api/write"
8
	"github.com/memnix/memnix-rest/infrastructures"
9
)
10
11
var logsChan = make(chan write.Point, 100) // buffered channel
12
13
// LogWriter is a custom writer for logs to be used
14
// It implements the io.Writer interface
15
type LogWriter struct{}
16
17
// Write is the implementation of the io.Writer interface
18
// It writes the log to the logsChan channel to be processed by the LogWorker
19
func (LogWriter) Write(p write.Point) (int, error) {
20
	logsChan <- p // write to channel
21
	return 1, nil
22
}
23
24
// LogWorker is the worker that will process the logsChan channel
25
func LogWorker(logs <-chan write.Point, wg *sync.WaitGroup) {
26
	defer wg.Done() // signal that we are done
27
28
	writeAPI := (*infrastructures.GetInfluxDBClient()).WriteAPI("memnix", "logs") // get writeAPI
29
30
	go func() {
31
		// Flush every 5s
32
		for range time.Tick(10 * time.Second) {
33
			writeAPI.Flush()
34
		}
35
	}()
36
37
	// Infinite loop
38
	for {
39
		logContent := <-logs
40
		writeAPI.WritePoint(&logContent)
41
	}
42
}
43
44
// CreateLogger creates a new LogWorker in a goroutine and waits for it to finish
45
func CreateLogger() {
46
	var wg sync.WaitGroup       // wait group
47
	wg.Add(1)                   // add one to wait group
48
	go LogWorker(logsChan, &wg) // start LogWorker in a goroutine
49
	wg.Wait()                   // wait for LogWorker to finish
50
}
51