go-log/default_writing_router.go

93 lines
2.2 KiB
Go
Raw Normal View History

2016-09-21 19:59:05 +00:00
package flog
import (
"github.com/reiver/go-dotquote"
"github.com/reiver/go-oi"
"fmt"
"io"
"time"
)
2016-09-21 23:30:35 +00:00
// NewDefaultWritingRouter returns an initialized DefaultWritingRouter
2016-09-21 19:59:05 +00:00
func NewDefaultWritingRouter(writer io.Writer) *DefaultWritingRouter {
2016-09-21 23:30:35 +00:00
return NewDefaultWritingRouterWithPrefix(writer, nil)
}
// NewDefaultWritingRouterWithPrefix returns an initialized DefaultWritingRouter
func NewDefaultWritingRouterWithPrefix(writer io.Writer, prefix map[string]interface{}) *DefaultWritingRouter {
var prefixBuffer []byte
if 0 < len(prefix) {
prefixBuffer = dotquote.AppendMap(prefixBuffer, prefix)
prefixBuffer = append(prefixBuffer, ' ')
2016-09-21 23:30:35 +00:00
}
2016-09-21 19:59:05 +00:00
router := DefaultWritingRouter{
writer:writer,
2016-09-21 23:30:35 +00:00
prefix:prefixBuffer,
2016-09-21 19:59:05 +00:00
}
return &router
}
// DefaultWritingRouter is a router that writes the log in a default format.
//
// A DefaultWritingRouter is appropriate for a production (i.e., "PROD")
// deployment enviornment.
type DefaultWritingRouter struct {
writer io.Writer
2016-09-21 23:30:35 +00:00
prefix []byte
2016-09-21 19:59:05 +00:00
}
func (router *DefaultWritingRouter) Route(message string, context map[string]interface{}) error {
if nil == router {
return errNilReceiver
}
writer := router.writer
if nil == writer {
// Nothing to do, so just return silently.
return nil
}
var buffer [512]byte
p := buffer[:0]
2016-09-21 23:30:35 +00:00
if prefix := router.prefix; 0 < len(prefix) {
p = append(p, prefix...)
}
2016-09-21 19:59:05 +00:00
p = dotquote.AppendString(p, message, "text")
p = append(p, ' ')
p = dotquote.AppendString(p, time.Now().String(), "when")
2019-07-12 04:27:37 +00:00
if trace := calltrace(); nil != trace {
p = append(p, ' ')
p = dotquote.AppendStrings(p, trace, "calltrace")
}
2016-09-21 19:59:05 +00:00
// If we have an error, then get the error.Error() into the log too.
if errorFieldValue, ok := context["~error"]; ok {
if err, ok := errorFieldValue.(error); ok {
p = append(p, ' ')
p = dotquote.AppendString(p, fmt.Sprintf("%T", err), "error", "type")
p = append(p, ' ')
p = dotquote.AppendString(p, err.Error(), "error", "text")
}
}
if 0 < len(context) {
2016-09-21 19:59:05 +00:00
p = append(p, ' ')
p = dotquote.AppendMap(p, context, "ctx")
2016-09-21 19:59:05 +00:00
}
2016-09-23 22:24:45 +00:00
p = append(p, '\n')
2016-09-21 19:59:05 +00:00
_,_ = oi.LongWrite(router.writer, p)
//@TODO: Should this be checking for errors from oi.LongWrite()?
return nil
}