Skip to content

Commit

Permalink
Added fatal log level for logging a statement then exiting
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthew Borders committed Nov 7, 2018
1 parent 088821d commit 6acbc15
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
1 change: 1 addition & 0 deletions level.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ const (
INFO
WARN
ERROR
FATAL
)
15 changes: 14 additions & 1 deletion logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package logmatic

import (
"fmt"
"os"
"time"

"github.com/fatih/color"
)

var printf = fmt.Printf
var exit = os.Exit

// logFunc represents a log function
type logFunc func(a ...interface{}) string
Expand All @@ -21,6 +23,7 @@ type Logger struct {
info logFunc
warn logFunc
error logFunc
fatal logFunc
}

func (l *Logger) now() string {
Expand Down Expand Up @@ -75,7 +78,16 @@ func (l *Logger) Warn(format string, a ...interface{}) {
// Error logs an error statement
// ERROR or lower (any level)
func (l *Logger) Error(format string, a ...interface{}) {
l.log(l.error("ERROR"), format, a...)
if l.level <= ERROR {
l.log(l.error("ERROR"), format, a...)
}
}

// Fatal logs an error statement and exits the application
// FATAL or lower (any level)
func (l *Logger) Fatal(format string, a ...interface{}) {
l.log(l.fatal("FATAL"), format, a...)
exit(1)
}

// NewLogger creates a new logger
Expand All @@ -88,5 +100,6 @@ func NewLogger() *Logger {
info: color.New(color.FgCyan).SprintFunc(),
warn: color.New(color.FgYellow).SprintFunc(),
error: color.New(color.FgRed).SprintFunc(),
fatal: color.New(color.FgRed, color.Bold).SprintFunc(),
}
}
20 changes: 20 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,23 @@ func TestLogger_Error_Print(t *testing.T) {
l.Error("Error")
assert.NotEmpty(t, buf)
}

func TestLogger_Error_NoPrint(t *testing.T) {
var buf bytes.Buffer
mockPrint(&buf)

l := NewLogger()
l.SetLevel(FATAL)
l.Error("Error")
assert.Empty(t, buf)
}

func TestLogger_Fatal_Print(t *testing.T) {
var buf bytes.Buffer
mockPrint(&buf)
exit = func(code int) {}

l := NewLogger()
l.Fatal("Fatal")
assert.NotEmpty(t, buf)
}

0 comments on commit 6acbc15

Please sign in to comment.