Merge pull request #2 from christopherhein/feature/timestamps-flag

adding support for turning off timestamps
rc-0.2.0
Kris Nova 2018-11-27 15:58:38 -08:00 committed by GitHub
commit fd0d87064b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 23 deletions

View File

@ -21,9 +21,8 @@ import (
"strings"
"time"
lol "github.com/kris-nova/lolgopher"
"github.com/fatih/color"
lol "github.com/kris-nova/lolgopher"
)
type Logger func(format string, a ...interface{})
@ -44,6 +43,7 @@ var (
FabulousWriter = lol.NewLolWriter()
FabulousTrueWriter = lol.NewTruecolorLolWriter()
TestMode = false
Timestamps = true
)
func Always(format string, a ...interface{}) {
@ -132,7 +132,6 @@ func Debug(format string, a ...interface{}) {
fmt.Fprintf(w, s)
}
}
@ -165,11 +164,18 @@ func extractLoggerArgs(format string, a ...interface{}) ([]interface{}, io.Write
}
}
return a, w
}
func label(format, label string) string {
if Timestamps {
return labelWithTime(format, label)
} else {
return labelWithoutTime(format, label)
}
}
func labelWithTime(format, label string) string {
t := time.Now()
rfct := t.Format(time.RFC3339)
if !strings.Contains(format, "\n") {
@ -177,3 +183,10 @@ func label(format, label string) string {
}
return fmt.Sprintf("%s [%s] %s", rfct, label, format)
}
func labelWithoutTime(format, label string) string {
if !strings.Contains(format, "\n") {
format = fmt.Sprintf("%s%s", format, "\n")
}
return fmt.Sprintf("[%s] %s", label, format)
}

View File

@ -18,13 +18,13 @@ import (
"bytes"
"fmt"
"regexp"
"strings"
"testing"
)
const (
format = "%v, %v, %v, all eyes on me!"
formatExp = `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.* \[%s\] \d, \d, \d, all eyes on me!`
format = "%v, %v, %v, all eyes on me!"
formatExp = `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.* \[%s\] \d, \d, \d, all eyes on me!`
formatWOTimeExp = `\[%s\] \d, \d, \d, all eyes on me!`
)
var (
@ -37,20 +37,6 @@ func TestMain(m *testing.M) {
m.Run()
}
func ExampleTestLog() {
Log(format, a...)
// Output: 1, 2, 3, all eyes on me!
}
func TestLog(t *testing.T) {
e := fmt.Sprintf(format, a...)
g := captureLoggerOutput(Log, format, a)
if strings.Compare(e, g) != 0 {
t.Fatalf("Log should produce '%v' but produces: %v", e, g)
}
}
func TestAlways(t *testing.T) {
e, err := regexp.Compile(fmt.Sprintf(formatExp, AlwaysLabel))
g := captureLoggerOutput(Always, format, a)
@ -139,6 +125,20 @@ func TestWarning(t *testing.T) {
}
}
func TestWithoutTimestamps(t *testing.T) {
Timestamps = false
e, err := regexp.Compile(fmt.Sprintf(formatWOTimeExp, AlwaysLabel))
g := captureLoggerOutput(Always, format, a)
if err != nil {
t.Fatalf("Failed to compile regexp '%v': %v", e.String(), err)
}
if !e.MatchString(g) {
t.Fatalf("Always should produce a pattern '%v' but produces: %v", e.String(), g)
}
}
func captureLoggerOutput(l Logger, format string, a []interface{}) string {
b := new(bytes.Buffer)
l(format, append(a, b)...)