Skip to content

Commit

Permalink
Merge pull request #36 from hashicorp/svh/f-level-writer
Browse files Browse the repository at this point in the history
Add a LevelWriter interface to use as leveled writer
  • Loading branch information
Sander van Harmelen authored Mar 1, 2019
2 parents 2f91710 + 968b51d commit 73fd499
Show file tree
Hide file tree
Showing 4 changed files with 160 additions and 29 deletions.
10 changes: 4 additions & 6 deletions intlogger.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package hclog

import (
"bufio"
"bytes"
"encoding"
"encoding/json"
"fmt"
"io"
"log"
"os"
"reflect"
"runtime"
"sort"
Expand Down Expand Up @@ -47,7 +45,7 @@ type intLogger struct {
// This is a pointer so that it's shared by any derived loggers, since
// those derived loggers share the bufio.Writer as well.
mutex *sync.Mutex
writer *bufio.Writer
writer *writer
level *int32

implied []interface{}
Expand All @@ -61,7 +59,7 @@ func New(opts *LoggerOptions) Logger {

output := opts.Output
if output == nil {
output = os.Stderr
output = DefaultOutput
}

level := opts.Level
Expand All @@ -80,7 +78,7 @@ func New(opts *LoggerOptions) Logger {
name: opts.Name,
timeFormat: TimeFormat,
mutex: mutex,
writer: bufio.NewWriter(output),
writer: newWriter(output),
level: new(int32),
}

Expand Down Expand Up @@ -111,7 +109,7 @@ func (l *intLogger) Log(level Level, msg string, args ...interface{}) {
l.log(t, level, msg, args...)
}

l.writer.Flush()
l.writer.Flush(level)
}

// Cleanup a path by returning the last 2 segments of the path only.
Expand Down
2 changes: 1 addition & 1 deletion logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

var (
//DefaultOutput is used as the default log output.
DefaultOutput = os.Stderr
DefaultOutput io.Writer = os.Stderr

// DefaultLevel is used as the default log level.
DefaultLevel = Info
Expand Down
103 changes: 81 additions & 22 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
"testing"
Expand All @@ -15,6 +16,23 @@ import (
)

func TestLogger(t *testing.T) {
t.Run("uses default output if none is given", func(t *testing.T) {
var buf bytes.Buffer
DefaultOutput = &buf

logger := New(&LoggerOptions{
Name: "test",
})

logger.Info("this is test", "who", "programmer", "why", "testing")

str := buf.String()
dataIdx := strings.IndexByte(str, ' ')
rest := str[dataIdx+1:]

assert.Equal(t, "[INFO] test: this is test: who=programmer why=testing\n", rest)
})

t.Run("formats log entries", func(t *testing.T) {
var buf bytes.Buffer

Expand All @@ -26,10 +44,7 @@ func TestLogger(t *testing.T) {
logger.Info("this is test", "who", "programmer", "why", "testing")

str := buf.String()

dataIdx := strings.IndexByte(str, ' ')

// ts := str[:dataIdx]
rest := str[dataIdx+1:]

assert.Equal(t, "[INFO] test: this is test: who=programmer why=testing\n", rest)
Expand All @@ -46,10 +61,7 @@ func TestLogger(t *testing.T) {
logger.Info("this is test", "who", "programmer", "why", "testing is fun")

str := buf.String()

dataIdx := strings.IndexByte(str, ' ')

// ts := str[:dataIdx]
rest := str[dataIdx+1:]

assert.Equal(t, "[INFO] test: this is test: who=programmer why=\"testing is fun\"\n", rest)
Expand All @@ -66,10 +78,7 @@ func TestLogger(t *testing.T) {
logger.Info("this is test", "who", "programmer", "why", []interface{}{"testing", "dev", 1, uint64(5), []int{3, 4}})

str := buf.String()

dataIdx := strings.IndexByte(str, ' ')

// ts := str[:dataIdx]
rest := str[dataIdx+1:]

assert.Equal(t, "[INFO] test: this is test: who=programmer why=[testing, dev, 1, 5, \"[3 4]\"]\n", rest)
Expand All @@ -86,10 +95,7 @@ func TestLogger(t *testing.T) {
logger.Info("this is test", "who", "programmer", "why", []string{"testing & qa", "dev"})

str := buf.String()

dataIdx := strings.IndexByte(str, ' ')

// ts := str[:dataIdx]
rest := str[dataIdx+1:]

assert.Equal(t, "[INFO] test: this is test: who=programmer why=[\"testing & qa\", dev]\n", rest)
Expand All @@ -106,7 +112,6 @@ func TestLogger(t *testing.T) {
logger.Info("who", "programmer", "why", "testing", Stacktrace())

lines := strings.Split(buf.String(), "\n")

require.True(t, len(lines) > 1)

assert.Equal(t, "github.com/hashicorp/go-hclog.Stacktrace", lines[1])
Expand All @@ -123,7 +128,6 @@ func TestLogger(t *testing.T) {
logger.Info("who", "programmer", "why", "testing", "foo", Stacktrace())

lines := strings.Split(buf.String(), "\n")

require.True(t, len(lines) > 1)

assert.Equal(t, "github.com/hashicorp/go-hclog.Stacktrace", lines[1])
Expand All @@ -141,14 +145,11 @@ func TestLogger(t *testing.T) {
logger.Info("this is test", "who", "programmer", "why", "testing is fun")

str := buf.String()

dataIdx := strings.IndexByte(str, ' ')

// ts := str[:dataIdx]
rest := str[dataIdx+1:]

// This test will break if you move this around, it's line dependent, just fyi
assert.Equal(t, "[INFO] go-hclog/logger_test.go:141: test: this is test: who=programmer why=\"testing is fun\"\n", rest)
assert.Equal(t, "[INFO] go-hclog/logger_test.go:145: test: this is test: who=programmer why=\"testing is fun\"\n", rest)
})

t.Run("prefixes the name", func(t *testing.T) {
Expand Down Expand Up @@ -187,7 +188,6 @@ func TestLogger(t *testing.T) {
logger.Info("this is test", "who", "programmer", "why", "testing is fun")

str := buf.String()

dataIdx := strings.IndexByte(str, ' ')

assert.Equal(t, str[:dataIdx], time.Now().Format(time.Kitchen))
Expand Down Expand Up @@ -329,16 +329,75 @@ func TestLogger(t *testing.T) {
logger.Info("this is test", "production", Fmt("%d beans/day", 12))

str := buf.String()

dataIdx := strings.IndexByte(str, ' ')

// ts := str[:dataIdx]
rest := str[dataIdx+1:]

assert.Equal(t, "[INFO] test: this is test: production=\"12 beans/day\"\n", rest)
})
}

func TestLogger_leveledWriter(t *testing.T) {
t.Run("writes errors to stderr", func(t *testing.T) {
var stderr bytes.Buffer
var stdout bytes.Buffer

logger := New(&LoggerOptions{
Name: "test",
Output: NewLevelWriter(&stdout, map[Level]io.Writer{Error: &stderr}),
})

logger.Error("this is an error", "who", "programmer", "why", "testing")

errStr := stderr.String()
errDataIdx := strings.IndexByte(errStr, ' ')
errRest := errStr[errDataIdx+1:]

assert.Equal(t, "[ERROR] test: this is an error: who=programmer why=testing\n", errRest)
})

t.Run("writes non-errors to stdout", func(t *testing.T) {
var stderr bytes.Buffer
var stdout bytes.Buffer

logger := New(&LoggerOptions{
Name: "test",
Output: NewLevelWriter(&stdout, map[Level]io.Writer{Error: &stderr}),
})

logger.Info("this is test", "who", "programmer", "why", "testing")

outStr := stdout.String()
outDataIdx := strings.IndexByte(outStr, ' ')
outRest := outStr[outDataIdx+1:]

assert.Equal(t, "[INFO] test: this is test: who=programmer why=testing\n", outRest)
})

t.Run("writes errors and non-errors correctly", func(t *testing.T) {
var stderr bytes.Buffer
var stdout bytes.Buffer

logger := New(&LoggerOptions{
Name: "test",
Output: NewLevelWriter(&stdout, map[Level]io.Writer{Error: &stderr}),
})

logger.Info("this is test", "who", "programmer", "why", "testing")
logger.Error("this is an error", "who", "programmer", "why", "testing")

errStr := stderr.String()
errDataIdx := strings.IndexByte(errStr, ' ')
errRest := errStr[errDataIdx+1:]

outStr := stdout.String()
outDataIdx := strings.IndexByte(outStr, ' ')
outRest := outStr[outDataIdx+1:]

assert.Equal(t, "[ERROR] test: this is an error: who=programmer why=testing\n", errRest)
assert.Equal(t, "[INFO] test: this is test: who=programmer why=testing\n", outRest)
})
}

func TestLogger_JSON(t *testing.T) {
t.Run("json formatting", func(t *testing.T) {
var buf bytes.Buffer
Expand Down
74 changes: 74 additions & 0 deletions writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package hclog

import (
"bytes"
"io"
)

type writer struct {
b bytes.Buffer
w io.Writer
}

func newWriter(w io.Writer) *writer {
return &writer{w: w}
}

func (w *writer) Flush(level Level) (err error) {
if lw, ok := w.w.(LevelWriter); ok {
_, err = lw.LevelWrite(level, w.b.Bytes())
} else {
_, err = w.w.Write(w.b.Bytes())
}
w.b.Reset()
return err
}

func (w *writer) Write(p []byte) (int, error) {
return w.b.Write(p)
}

func (w *writer) WriteByte(c byte) error {
return w.b.WriteByte(c)
}

func (w *writer) WriteString(s string) (int, error) {
return w.b.WriteString(s)
}

// LevelWriter is the interface that wraps the LevelWrite method.
type LevelWriter interface {
LevelWrite(level Level, p []byte) (n int, err error)
}

// LeveledWriter writes all log messages to the standard writer,
// except for log levels that are defined in the overrides map.
type LeveledWriter struct {
standard io.Writer
overrides map[Level]io.Writer
}

// NewLevelWriter returns an initialized LeveledWriter.
//
// standard will be used as the default writer for all log levels,
// except for log levels that are defined in the overrides map.
func NewLevelWriter(standard io.Writer, overrides map[Level]io.Writer) *LeveledWriter {
return &LeveledWriter{
standard: standard,
overrides: overrides,
}
}

// Write implements io.Writer.
func (lw *LeveledWriter) Write(p []byte) (int, error) {
return lw.standard.Write(p)
}

// LevelWrite implements LevelWriter.
func (lw *LeveledWriter) LevelWrite(level Level, p []byte) (int, error) {
w, ok := lw.overrides[level]
if !ok {
w = lw.standard
}
return w.Write(p)
}

0 comments on commit 73fd499

Please sign in to comment.