Skip to content

Commit 057ebef

Browse files
committed
Merge pull request #53 from purpleidea/feat/simple-formatter
Offer the ability to pass through standard capnslog when embedding.
2 parents 1914e36 + 68c9954 commit 057ebef

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

capnslog/formatters.go

Lines changed: 32 additions & 1 deletion
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"
@@ -28,7 +29,7 @@ type Formatter interface {
2829
Flush()
2930
}
3031

31-
func NewStringFormatter(w io.Writer) *StringFormatter {
32+
func NewStringFormatter(w io.Writer) Formatter {
3233
return &StringFormatter{
3334
w: bufio.NewWriter(w),
3435
}
@@ -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) Formatter {
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 (lf *LogFormatter) Format(pkg string, _ LogLevel, _ int, entries ...interface{}) {
126+
str := fmt.Sprint(entries...)
127+
prefix := lf.prefix
128+
if pkg != "" {
129+
prefix = fmt.Sprintf("%s%s: ", prefix, pkg)
130+
}
131+
lf.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 a no-op.
135+
func (lf *LogFormatter) Flush() {
136+
// noop
137+
}

0 commit comments

Comments
 (0)