57 lines
819 B
Go
57 lines
819 B
Go
package slog
|
|
|
|
import (
|
|
"io"
|
|
"time"
|
|
)
|
|
|
|
type ChannelLogger struct {
|
|
w chan string
|
|
b bool
|
|
t *time.Duration
|
|
}
|
|
|
|
func (c *ChannelLogger) Write(p []byte) (n int, err error) {
|
|
if c.b {
|
|
c.blockWrite(p)
|
|
} else {
|
|
c.nonBlockWrite(p)
|
|
}
|
|
|
|
return len(p), nil
|
|
}
|
|
|
|
func (c *ChannelLogger) Close() error {
|
|
return nil
|
|
}
|
|
|
|
func (c *ChannelLogger) blockWrite(p []byte) {
|
|
if c.t == nil {
|
|
c.w <- string(p)
|
|
return
|
|
}
|
|
|
|
select {
|
|
case c.w <- string(p):
|
|
return
|
|
case <-time.After(*c.t):
|
|
return
|
|
}
|
|
}
|
|
|
|
func (c *ChannelLogger) nonBlockWrite(p []byte) {
|
|
select {
|
|
case c.w <- string(p):
|
|
return
|
|
}
|
|
}
|
|
|
|
func NewChannelLogger(block bool, buffer int, timeout *time.Duration) (ret io.Writer, cret chan string) {
|
|
rret := &ChannelLogger{}
|
|
rret.w = make(chan string, buffer)
|
|
rret.b = block
|
|
rret.t = timeout
|
|
|
|
return rret, rret.w
|
|
}
|