-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoutput.go
91 lines (75 loc) · 1.96 KB
/
output.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
82
83
84
85
86
87
88
89
90
91
package logri
import (
"bytes"
"errors"
"io"
"os"
"runtime"
"sync"
)
type OutputType string
const (
FileOutput OutputType = "file"
StdoutOutput = "stdout"
StderrOutput = "stderr"
TestOutput = "test" // Used for tests only
)
var (
ErrInvalidOutputOptions = errors.New("Insufficient or invalid options were given for an output")
// Registry of file outputs
fileOutputRegistry = make(map[string]io.Writer)
// Registry of test outputs
testOutputRegistry = make(map[string]*bytes.Buffer)
mu sync.Mutex
)
func GetOutputWriter(outtype OutputType, options map[string]string) (io.Writer, error) {
switch outtype {
case FileOutput:
// FileOutput type requires an option called "file," specifying the
// file to be logged to. If it doesn't exist, it's invalid config.
file, ok := options["file"]
if !ok {
return nil, ErrInvalidOutputOptions
}
// Look to see if we have a writer open already
mu.Lock()
defer mu.Unlock()
if writer, ok := fileOutputRegistry[file]; ok {
return writer, nil
}
// Open the file for appending, creating if it exists, and save the
// writer for later access by other loggers.
writer, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return nil, err
}
fileOutputRegistry[file] = writer
// Close the file if it gets GCed
runtime.SetFinalizer(writer, finalizeFile)
return writer, nil
case StdoutOutput:
return os.Stdout, nil
case StderrOutput:
return os.Stderr, nil
case TestOutput:
name, ok := options["name"]
if !ok {
return nil, ErrInvalidOutputOptions
}
mu.Lock()
defer mu.Unlock()
if writer, ok := testOutputRegistry[name]; ok {
return writer, nil
}
var writer bytes.Buffer
testOutputRegistry[name] = &writer
return &writer, nil
}
return nil, ErrInvalidOutputOptions
}
func finalizeFile(f *os.File) {
mu.Lock()
defer mu.Unlock()
delete(fileOutputRegistry, f.Name())
f.Close()
}