diff --git a/Makefile b/Makefile index 565418a9a..06f7d77c7 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 e0322d3cd..0ecda2a24 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -15,6 +15,7 @@ package log import ( + "fmt" "io" "log" "os" @@ -28,31 +29,34 @@ 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) } // 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 @@ -69,3 +73,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) })