-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
57 lines (48 loc) · 1.89 KB
/
writer.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
package olog
import (
"io"
"os"
)
// csWriter is a variable that holds a new instance of consoleWriter created by calling the NewConsoleWriter function
var csWriter = NewConsoleWriter()
// Writer is an interface that defines a Write method with a Level and a byte slice as its parameters and returns an integer and an error
// Special attention must be paid to the fact that p []byte should not exceed the scope of the Write method.
// After the Write method ends, the byte slice should not be used, otherwise will cause memory data errors.
type Writer interface {
Write(level Level, p []byte) (n int, err error)
}
// consoleWriter is a struct that holds a standard output wr and a standard error wr
type consoleWriter struct {
sw io.Writer
ew io.Writer
}
// Write is a method on consoleWriter that writes the byte slice p to the standard wr or the error wr depending on the level parameter
func (c *consoleWriter) Write(level Level, p []byte) (n int, err error) {
if level >= WARN {
return c.ew.Write(p)
}
return c.sw.Write(p)
}
// customWriter is a struct that holds a custom wr
type customWriter struct {
w io.Writer
}
// Write is a method on customWriter that writes the byte slice p to the custom wr
func (c *customWriter) Write(level Level, p []byte) (n int, err error) {
return c.w.Write(p)
}
// NewConsoleWriter is a function that creates a new consoleWriter with os.Stdout as the standard wr and os.Stderr as the error wr
func NewConsoleWriter() Writer {
return &consoleWriter{
sw: os.Stdout,
ew: os.Stderr,
}
}
// NewWriter is a function that creates a new customWriter with the specified wr as its parameter
// Special attention must be paid to the fact that []byte should not exceed the scope of the Write method.
// After the Write method ends, the byte slice should not be used, otherwise will cause memory data errors.
func NewWriter(w io.Writer) Writer {
return &customWriter{
w: w,
}
}