Skip to content

Commit

Permalink
Merge 469377f into 920ccb4
Browse files Browse the repository at this point in the history
  • Loading branch information
martinilevi committed Apr 3, 2018
2 parents 920ccb4 + 469377f commit 90dda25
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
10 changes: 10 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,16 @@ func (l *Logger) GetLevel() string {
return LogLevelNames[l.logLevel]
}

// SetWriter to set the log writer
func (l *Logger) SetWriter(o io.Writer) {
l.out = o
}

// GetWriter to get the log writer
func (l *Logger) GetWriter() io.Writer {
return l.out
}

func (l *Logger) log(logLevel level, context interface{}, message string, args ...interface{}) {
if logLevel >= l.logLevel {
var buf bytes.Buffer
Expand Down
54 changes: 54 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import (
"strings"
"testing"
"time"
"os"
"bufio"
"io/ioutil"
"encoding/json"
)

func TestLevelByName(t *testing.T) {
Expand Down Expand Up @@ -68,6 +72,56 @@ func TestLoggerLevel(t *testing.T) {
SetDefaultLogLevel("INFO")
}

func TestLoggerOutput(t *testing.T) {
const TestFile = "/tmp/random.log"
fd, err := os.Create(TestFile)
if err != nil {
t.Errorf("Couldn't create %s file: %s", TestFile, err.Error())
return
}

writer := bufio.NewWriter(fd)
logger := NewLogger()
logger.SetWriter(writer)
expectedMsg := "hola"
logger.Info(expectedMsg)
writer.Flush()

content, err := ioutil.ReadFile(TestFile)
if err != nil {
t.Errorf("Couldn't read %s file: %s", TestFile, err.Error())
return
}

parsed := map[string]interface{}{}

err = json.Unmarshal(content, &parsed)
if err != nil {
t.Errorf("Couldn't unmarshal %s file: %s", TestFile, err.Error())
return
}

expectedLevel := logger.GetLevel()
gotLevel := parsed["lvl"].(string)
if expectedLevel != gotLevel {
t.Errorf("Expecting level \"%s\", got \"%s\" instead.", expectedLevel, gotLevel)
}

gotMsg := parsed["msg"].(string)
if expectedMsg != gotMsg {
t.Errorf("Expecting msg \"%s\", got \"%s\" instead.", expectedMsg, gotMsg)
}

logger.SetWriter(os.Stdout)

new := logger.GetWriter()

if new != os.Stdout {
t.Error("Not expected output writer interface")
}
}


func TestLoggerContext(t *testing.T) {
logger := NewLogger()
if logger.GetLogContext() != nil {
Expand Down

0 comments on commit 90dda25

Please sign in to comment.