Skip to content

Commit 9aa8a60

Browse files
committed
Add a smarter formatter to simulate the normal log behaviour
This adds a more clever formatter that uses the logger call depth to return accurate data about the logged message in question. It can be called with: capnslog.SetFormatter( capnslog.NewLogFormatter(os.Stderr, "<prefix> ", flags) )
1 parent 1914e36 commit 9aa8a60

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

capnslog/formatters.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"bufio"
1919
"fmt"
2020
"io"
21+
"log"
2122
"runtime"
2223
"strings"
2324
"time"
@@ -104,3 +105,33 @@ func (c *PrettyFormatter) Format(pkg string, l LogLevel, depth int, entries ...i
104105
func (c *PrettyFormatter) Flush() {
105106
c.w.Flush()
106107
}
108+
109+
// LogFormatter emulates the form of the traditional built-in logger.
110+
type LogFormatter struct {
111+
logger *log.Logger
112+
prefix string
113+
}
114+
115+
// NewLogFormatter is a helper to produce a new LogFormatter struct. It uses the
116+
// golang log package to actually do the logging work so that logs look similar.
117+
func NewLogFormatter(w io.Writer, prefix string, flag int) *LogFormatter {
118+
return &LogFormatter{
119+
logger: log.New(w, "", flag), // don't use prefix here
120+
prefix: prefix, // save it instead
121+
}
122+
}
123+
124+
// Format builds a log message for the LogFormatter. The LogLevel is ignored.
125+
func (s *LogFormatter) Format(pkg string, l LogLevel, i int, entries ...interface{}) {
126+
str := fmt.Sprint(entries...)
127+
prefix := s.prefix
128+
if pkg != "" {
129+
prefix = fmt.Sprintf("%s%s: ", prefix, pkg)
130+
}
131+
s.logger.Output(5, fmt.Sprintf("%s%v", prefix, str)) // call depth is 5
132+
}
133+
134+
// Flush is included so that the interface is complete, but is not used.
135+
func (s *LogFormatter) Flush() {
136+
// noop
137+
}

0 commit comments

Comments
 (0)