Skip to content

Commit

Permalink
Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
maxence-charriere committed Sep 30, 2017
1 parent 8df4e26 commit fd65d75
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 0 deletions.
19 changes: 19 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package app

// A Logger represents an active logging object that generates lines of output.
type Logger interface {
// Log logs a message using the default formats for its operands.
// Spaces are always added between operands and a newline is appended.
Log(v ...interface{})

// Logf logs a message according to a format specifier.
Logf(format string, v ...interface{})

// Log logs an error using the default formats for its operands.
// Spaces are always added between operands and a newline is appended.
Error(v ...interface{})

// Logf logs an error according to a format specifier.
Errorf(format string, v ...interface{})
}

58 changes: 58 additions & 0 deletions log/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package log

import "runtime"
import "path/filepath"
import "fmt"
import "strings"

const (
defaultColor string = "\033[00m"
accentColor string = "\033[94m"
errColor string = "\033[91m"
)

// Logger is a logger that satisfies the app.Logger interface.
type Logger struct {
Debug bool
}

// Log satisfies the app.Logger interface.
func (l *Logger) Log(v ...interface{}) {
if !l.Debug {
return
}
printPrefix("Log", accentColor)
fmt.Println(v...)
}

// Logf satisfies the app.Logger interface.
func (l *Logger) Logf(format string, v ...interface{}) {
if !l.Debug {
return
}
printPrefix("Log", accentColor)
fmt.Printf(format, v...)
}

// Error satisfies the app.Logger interface.
func (l *Logger) Error(v ...interface{}) {
printPrefix("Error", errColor)
fmt.Println(v...)
}

// Errorf satisfies the app.Logger interface.
func (l *Logger) Errorf(format string, v ...interface{}) {
printPrefix("Error", errColor)
fmt.Printf(format, v...)
}

func printPrefix(level, color string) {
file, line := caller()
fmt.Printf("%s%s%s - %s: %v - ", color, strings.ToUpper(level), defaultColor, file, line)
}

func caller() (file string, line int) {
_, file, line, _ = runtime.Caller(3)
file = filepath.Base(file)
return
}
18 changes: 18 additions & 0 deletions log/log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package log

import "testing"

func TestLogger(t *testing.T) {
l := Logger{}

l.Log("hello", "world")
l.Logf("%s %s\n", "hello", "world")

l.Debug = true

l.Log("hello", "world")
l.Logf("%s %s\n", "hello", "world")

l.Error("hello", "world")
l.Errorf("%s %s\n", "hello", "world")
}

0 comments on commit fd65d75

Please sign in to comment.