-
Notifications
You must be signed in to change notification settings - Fork 23
/
handler_stream.go
77 lines (65 loc) · 1.94 KB
/
handler_stream.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
package logging
// An interface to stream abstraction.
type Stream interface {
// Report the current offset in the stream.
Tell() (offset int64, err error)
// Write a string into the stream.
Write(s string) error
// Flush the stream.
Flush() error
// Close the stream.
Close() error
}
// A handler class with writes logging records, appropriately formatted,
// to a stream. Note that this class doesn't close the stream, as os.Stdin or
// os.Stdout my be used. However a Close2() method is there for subclass.
type StreamHandler struct {
*BaseHandler
stream Stream
}
// Initialize a stream handler with name, logging level and underlying stream.
func NewStreamHandler(
name string, level LogLevelType, stream Stream) *StreamHandler {
object := &StreamHandler{
BaseHandler: NewBaseHandler(name, level),
stream: stream,
}
Closer.AddHandler(object)
return object
}
// Return the underlying stream.
func (self *StreamHandler) GetStream() Stream {
return self.stream
}
// Set the underlying stream.
func (self *StreamHandler) SetStream(s Stream) {
self.stream = s
}
// Emit a record.
func (self *StreamHandler) Emit(record *LogRecord) error {
return self.Emit2(self, record)
}
// A helper function to emit a record.
// If a formatter is specified, it is used to format the record.
// The record is then written to the stream with a trailing newline.
func (self *StreamHandler) Emit2(
handler Handler, record *LogRecord) error {
message := handler.Format(record)
if err := self.stream.Write(message); err != nil {
return err
}
return nil
}
// Handle() function is for the usage of stream handler on its own.
func (self *StreamHandler) Handle(record *LogRecord) int {
return self.BaseHandler.Handle2(self, record)
}
// Flush the stream.
func (self *StreamHandler) Flush() error {
return self.stream.Flush()
}
// A helper function for subclass implementation to close stream.
func (self *StreamHandler) Close2() {
self.Flush()
self.stream.Close()
}