[TASK] add test to log hook output

This commit is contained in:
Martin Geno 2017-06-14 23:52:38 +02:00
parent 5aff5e58fa
commit 8ca34866fd
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
3 changed files with 77 additions and 5 deletions

View File

@ -4,6 +4,7 @@ package output
import ( import (
"fmt" "fmt"
"io"
"os" "os"
"time" "time"
@ -13,9 +14,11 @@ import (
) )
var ( var (
TimeFormat = "2006-01-02 15:04:05" TimeFormat = "2006-01-02 15:04:05"
ShowTime = true ShowTime = true
AboveLevel = log.InfoLevel AboveLevel = log.InfoLevel
errOutput io.Writer = os.Stderr
output io.Writer = os.Stdout
) )
// logger for output // logger for output
@ -76,9 +79,9 @@ func (l *Logger) Hook(e *log.Entry) {
text := fmt.Sprintf(format, v...) text := fmt.Sprintf(format, v...)
if e.Level > log.WarnLevel { if e.Level > log.WarnLevel {
os.Stderr.WriteString(text) errOutput.Write([]byte(text))
} else { } else {
os.Stdout.WriteString(text) output.Write([]byte(text))
} }
} }

View File

@ -1 +1,69 @@
package output package output
import (
"bytes"
"os"
"testing"
"github.com/genofire/logmania/log"
"github.com/stretchr/testify/assert"
)
func captureOutput(f func()) (string, string) {
var bufErrOutput bytes.Buffer
var bufOutput bytes.Buffer
errOutput = &bufErrOutput
output = &bufOutput
f()
errOutput = os.Stderr
output = os.Stdout
return bufOutput.String(), bufErrOutput.String()
}
// Warning: colors are not tested (it should be in the imported package)
func TestOutput(t *testing.T) {
assert := assert.New(t)
assert.True(true)
out, err := captureOutput(func() {
log.Info("test")
})
assert.Regexp("-.*\\[.{5}Info.{4}\\] test", out)
assert.Equal("", err)
ShowTime = false
out, err = captureOutput(func() {
log.Warn("test")
})
assert.Regexp("\\[.{5}Warn.{4}\\] test", out)
assert.NotRegexp("-.*\\[.{5}Warn.{4}\\] test", out)
assert.Equal("", err)
out, err = captureOutput(func() {
log.Error("test")
})
assert.Equal("", out)
assert.Regexp("\\[.{5}ERROR.{4}\\] test", err)
out, err = captureOutput(func() {
log.Debug("test")
})
assert.Equal("", out)
assert.Equal("", err)
AboveLevel = log.DebugLevel
out, err = captureOutput(func() {
log.New().AddField("a", 3).Debug("test")
})
assert.Regexp("\\[.{5}Debug.{4}\\] test .{8}(a=3)", out)
assert.Equal("", err)
log.RemoveLogger("output")
out, err = captureOutput(func() {
log.Info("test")
})
assert.Equal("", out)
assert.Equal("", err)
}

View File

@ -13,6 +13,7 @@ func AddLogger(name string, logger Logger) {
loggers[name] = logger loggers[name] = logger
} }
func RemoveLogger(name string) { func RemoveLogger(name string) {
loggers[name].Close()
delete(loggers, name) delete(loggers, name)
} }