-
Notifications
You must be signed in to change notification settings - Fork 91
/
logging.go
81 lines (65 loc) · 1.5 KB
/
logging.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
package embeddedpostgres
import (
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
type syncedLogger struct {
offset int64
logger io.Writer
file *os.File
}
func newSyncedLogger(dir string, logger io.Writer) (*syncedLogger, error) {
file, err := os.CreateTemp(dir, "embedded_postgres_log")
if err != nil {
return nil, err
}
s := syncedLogger{
logger: logger,
file: file,
}
return &s, nil
}
func (s *syncedLogger) flush() error {
if s.logger != nil {
file, err := os.Open(s.file.Name())
if err != nil {
return fmt.Errorf("unable to process postgres logs: %s", err)
}
defer func() {
if err := file.Close(); err != nil {
panic(err)
}
}()
if _, err = file.Seek(s.offset, io.SeekStart); err != nil {
return fmt.Errorf("unable to process postgres logs: %s", err)
}
readBytes, err := io.Copy(s.logger, file)
if err != nil {
return fmt.Errorf("unable to process postgres logs: %s", err)
}
s.offset += readBytes
}
return nil
}
func readLogsOrTimeout(logger *os.File) (logContent []byte, err error) {
logContent = []byte("logs could not be read")
logContentChan := make(chan []byte, 1)
errChan := make(chan error, 1)
go func() {
if actualLogContent, err := ioutil.ReadFile(logger.Name()); err == nil {
logContentChan <- actualLogContent
} else {
errChan <- err
}
}()
select {
case logContent = <-logContentChan:
case err = <-errChan:
case <-time.After(10 * time.Second):
err = fmt.Errorf("timed out waiting for logs")
}
return logContent, err
}