Extract log utils into pkg/log

Docker-DCO-1.1-Signed-off-by: Josiah Kiehl <josiah@capoferro.net> (github: capoferro)
This commit is contained in:
Josiah Kiehl 2014-07-24 13:37:44 -07:00 committed by Erik Hollensbe
parent f5d12e100c
commit 6d4b3605f7
5 changed files with 123 additions and 7 deletions

77
log/log.go Normal file
View file

@ -0,0 +1,77 @@
package log
import (
"fmt"
"io"
"os"
"runtime"
"strings"
)
type priority int
const (
errorFormat = "[%s] %s:%d %s\n"
logFormat = "[%s] %s\n"
fatal priority = iota
error
info
debug
)
func (p priority) String() string {
switch p {
case fatal:
return "fatal"
case error:
return "error"
case info:
return "info"
case debug:
return "debug"
}
return ""
}
// Debug function, if the debug flag is set, then display. Do nothing otherwise
// If Docker is in damon mode, also send the debug info on the socket
func Debugf(format string, a ...interface{}) {
if os.Getenv("DEBUG") != "" {
logf(os.Stderr, debug, format, a...)
}
}
func Infof(format string, a ...interface{}) {
logf(os.Stdout, info, format, a...)
}
func Errorf(format string, a ...interface{}) {
logf(os.Stderr, error, format, a...)
}
func Fatalf(format string, a ...interface{}) {
logf(os.Stderr, fatal, format, a...)
os.Exit(1)
}
func logf(stream io.Writer, level priority, format string, a ...interface{}) {
var prefix string
if level <= error || level == debug {
// Retrieve the stack infos
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "<unknown>"
line = -1
} else {
file = file[strings.LastIndex(file, "/")+1:]
}
prefix = fmt.Sprintf(errorFormat, level.String(), file, line, format)
} else {
prefix = fmt.Sprintf(logFormat, level.String(), format)
}
fmt.Fprintf(stream, prefix, a...)
}

37
log/log_test.go Normal file
View file

@ -0,0 +1,37 @@
package log
import (
"bytes"
"regexp"
"testing"
)
func TestLogFatalf(t *testing.T) {
var output *bytes.Buffer
tests := []struct {
Level priority
Format string
Values []interface{}
ExpectedPattern string
}{
{fatal, "%d + %d = %d", []interface{}{1, 1, 2}, "\\[fatal\\] testing.go:\\d+ 1 \\+ 1 = 2"},
{error, "%d + %d = %d", []interface{}{1, 1, 2}, "\\[error\\] testing.go:\\d+ 1 \\+ 1 = 2"},
{info, "%d + %d = %d", []interface{}{1, 1, 2}, "\\[info\\] 1 \\+ 1 = 2"},
{debug, "%d + %d = %d", []interface{}{1, 1, 2}, "\\[debug\\] testing.go:\\d+ 1 \\+ 1 = 2"},
}
for i, test := range tests {
output = &bytes.Buffer{}
logf(output, test.Level, test.Format, test.Values...)
expected := regexp.MustCompile(test.ExpectedPattern)
if !expected.MatchString(output.String()) {
t.Errorf("[%d] Log output does not match expected pattern:\n\tExpected: %s\n\tOutput: %s",
i,
expected.String(),
output.String())
}
}
}