-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiwriter.go
64 lines (52 loc) · 1.24 KB
/
multiwriter.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
package main
import (
"bytes"
"io"
"os"
"sync"
)
// MultiWriter is a struct that writes logs to both a file and memory buffer.
type MultiWriter struct {
fileWriter io.Writer
memBuffer *bytes.Buffer
mutex sync.Mutex
}
// NewMultiWriter creates a new instance of MultiWriter.
func NewMultiWriter(filePath string) (*MultiWriter, error) {
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
return &MultiWriter{
fileWriter: file,
memBuffer: bytes.NewBuffer(nil),
}, nil
}
// Write writes the provided data to both file and memory buffer.
func (mw *MultiWriter) Write(p []byte) (n int, err error) {
mw.mutex.Lock()
defer mw.mutex.Unlock()
// Write to file
_, err = mw.fileWriter.Write(p)
if err != nil {
return 0, err
}
// Write to memory buffer
n, err = mw.memBuffer.Write(p)
if err != nil {
return 0, err
}
return n, nil
}
// ReadLastLines reads the last n lines from the memory buffer.
func (mw *MultiWriter) ReadLastLines(n int) []byte {
mw.mutex.Lock()
defer mw.mutex.Unlock()
buffer := mw.memBuffer.Bytes()
lines := bytes.Split(buffer, []byte("\n"))
start := len(lines) - n
if start < 0 {
start = 0
}
return bytes.Join(lines[start:], []byte("\n"))
}