diff --git a/Makefile b/Makefile index ed7f8640c..4709b20d5 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ SHELL := /bin/bash GIT_VERSION ?= v0.1.0 GIT_MODULE ?= opendev.org/airship/airshipctl/pkg/version -GO_FLAGS := -ldflags '-extldflags "-static"' -tags=netgo +GO_FLAGS := -ldflags '-extldflags "-static"' -tags=netgo -trimpath GO_FLAGS += -ldflags "-X ${GIT_MODULE}.gitVersion=${GIT_VERSION}" BINDIR := bin diff --git a/pkg/log/log.go b/pkg/log/log.go index 7d1e0dced..838f6cc88 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -15,6 +15,7 @@ package log import ( + "fmt" "io" "log" "os" @@ -28,6 +29,9 @@ var ( // Init initializes settings related to logging func Init(debugFlag bool, out io.Writer) { debug = debugFlag + if debug { + airshipLog.SetFlags(log.LstdFlags | log.Llongfile) + } airshipLog.SetOutput(out) } @@ -39,25 +43,25 @@ func DebugEnabled() bool { // Debug is a wrapper for log.Debug func Debug(v ...interface{}) { if debug { - airshipLog.Print(v...) + writeLog(v...) } } // Debugf is a wrapper for log.Debugf func Debugf(format string, v ...interface{}) { if debug { - airshipLog.Printf(format, v...) + writeLog(fmt.Sprintf(format, v...)) } } // Print is a wrapper for log.Print func Print(v ...interface{}) { - airshipLog.Print(v...) + writeLog(v...) } // Printf is a wrapper for log.Printf func Printf(format string, v ...interface{}) { - airshipLog.Printf(format, v...) + writeLog(fmt.Sprintf(format, v...)) } // Fatal is a wrapper for log.Fatal @@ -74,3 +78,15 @@ func Fatalf(format string, v ...interface{}) { func Writer() io.Writer { return airshipLog.Writer() } + +func writeLog(v ...interface{}) { + if debug { + err := airshipLog.Output(3, fmt.Sprint(v...)) + if err != nil { + log.Print(v...) + log.Print(err) + } + } else { + airshipLog.Print(v...) + } +} diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index cb134eec9..3bf4d8561 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -17,6 +17,7 @@ package log_test import ( "bytes" "regexp" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -73,7 +74,8 @@ func TestLoggingDebug(t *testing.T) { expected := "DebugTrue args 5\n" require.Regexp(logFormatRegex, actual) - actual = actual[prefixLength:] + lastIndex := strings.LastIndex(actual, ":") + actual = actual[lastIndex+2:] assert.Equal(expected, actual) }) @@ -86,7 +88,8 @@ func TestLoggingDebug(t *testing.T) { expected := "DebugfTrue args 5\n" require.Regexp(logFormatRegex, actual) - actual = actual[prefixLength:] + lastIndex := strings.LastIndex(actual, ":") + actual = actual[lastIndex+2:] assert.Equal(expected, actual) })