http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/Godeps/_workspace/src/github.com/spf13/cast/cast_test.go ---------------------------------------------------------------------- diff --git a/newt/Godeps/_workspace/src/github.com/spf13/cast/cast_test.go b/newt/Godeps/_workspace/src/github.com/spf13/cast/cast_test.go index e08887b..3fbcf87 100644 --- a/newt/Godeps/_workspace/src/github.com/spf13/cast/cast_test.go +++ b/newt/Godeps/_workspace/src/github.com/spf13/cast/cast_test.go @@ -23,6 +23,17 @@ func TestToInt(t *testing.T) { assert.Equal(t, ToInt(eight), 8) } +func TestToInt64(t *testing.T) { + var eight interface{} = 8 + assert.Equal(t, ToInt64(int64(8)), int64(8)) + assert.Equal(t, ToInt64(8), int64(8)) + assert.Equal(t, ToInt64(8.31), int64(8)) + assert.Equal(t, ToInt64("8"), int64(8)) + assert.Equal(t, ToInt64(true), int64(1)) + assert.Equal(t, ToInt64(false), int64(0)) + assert.Equal(t, ToInt64(eight), int64(8)) +} + func TestToFloat64(t *testing.T) { var eight interface{} = 8 assert.Equal(t, ToFloat64(8), 8.00) @@ -34,10 +45,14 @@ func TestToFloat64(t *testing.T) { func TestToString(t *testing.T) { var foo interface{} = "one more time" assert.Equal(t, ToString(8), "8") + assert.Equal(t, ToString(int64(16)), "16") assert.Equal(t, ToString(8.12), "8.12") assert.Equal(t, ToString([]byte("one time")), "one time") assert.Equal(t, ToString(template.HTML("one time")), "one time") assert.Equal(t, ToString(template.URL("http://somehost.foo")), "http://somehost.foo") + assert.Equal(t, ToString(template.JS("(1+2)")), "(1+2)") + assert.Equal(t, ToString(template.CSS("a")), "a") + assert.Equal(t, ToString(template.HTMLAttr("a")), "a") assert.Equal(t, ToString(foo), "one more time") assert.Equal(t, ToString(nil), "") assert.Equal(t, ToString(true), "true")
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/Godeps/_workspace/src/github.com/spf13/cast/caste.go ---------------------------------------------------------------------- diff --git a/newt/Godeps/_workspace/src/github.com/spf13/cast/caste.go b/newt/Godeps/_workspace/src/github.com/spf13/cast/caste.go index 3ac4cb7..2377896 100644 --- a/newt/Godeps/_workspace/src/github.com/spf13/cast/caste.go +++ b/newt/Godeps/_workspace/src/github.com/spf13/cast/caste.go @@ -111,6 +111,42 @@ func ToFloat64E(i interface{}) (float64, error) { } } +// ToInt64E casts an empty interface to an int64. +func ToInt64E(i interface{}) (int64, error) { + i = indirect(i) + jww.DEBUG.Println("ToInt64E called on type:", reflect.TypeOf(i)) + + switch s := i.(type) { + case int64: + return s, nil + case int: + return int64(s), nil + case int32: + return int64(s), nil + case int16: + return int64(s), nil + case int8: + return int64(s), nil + case string: + v, err := strconv.ParseInt(s, 0, 0) + if err == nil { + return v, nil + } + return 0, fmt.Errorf("Unable to Cast %#v to int64", i) + case float64: + return int64(s), nil + case bool: + if bool(s) { + return int64(1), nil + } + return int64(0), nil + case nil: + return int64(0), nil + default: + return int64(0), fmt.Errorf("Unable to Cast %#v to int64", i) + } +} + // ToIntE casts an empty interface to an int. func ToIntE(i interface{}) (int, error) { i = indirect(i) @@ -198,6 +234,8 @@ func ToStringE(i interface{}) (string, error) { return strconv.FormatBool(s), nil case float64: return strconv.FormatFloat(i.(float64), 'f', -1, 64), nil + case int64: + return strconv.FormatInt(i.(int64), 10), nil case int: return strconv.FormatInt(int64(i.(int)), 10), nil case []byte: @@ -206,6 +244,12 @@ func ToStringE(i interface{}) (string, error) { return string(s), nil case template.URL: return string(s), nil + case template.JS: + return string(s), nil + case template.CSS: + return string(s), nil + case template.HTMLAttr: + return string(s), nil case nil: return "", nil case fmt.Stringer: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra.go ---------------------------------------------------------------------- diff --git a/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra.go b/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra.go index 7c8da2b..7572ddf 100644 --- a/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra.go +++ b/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra.go @@ -27,11 +27,12 @@ import ( ) var templateFuncs template.FuncMap = template.FuncMap{ - "trim": strings.TrimSpace, - "trimRightSpace": trimRightSpace, - "rpad": rpad, - "gt": Gt, - "eq": Eq, + "trim": strings.TrimSpace, + "trimRightSpace": trimRightSpace, + "appendIfNotPresent": appendIfNotPresent, + "rpad": rpad, + "gt": Gt, + "eq": Eq, } var initializers []func() @@ -111,6 +112,14 @@ func trimRightSpace(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) } +// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s +func appendIfNotPresent(s, stringToAppend string) string { + if strings.Contains(s, stringToAppend) { + return s + } + return s + " " + stringToAppend +} + //rpad adds padding to the right of a string func rpad(s string, padding int) string { template := fmt.Sprintf("%%-%ds", padding) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go ---------------------------------------------------------------------- diff --git a/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go b/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go index e8c770f..99dafde 100644 --- a/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go +++ b/newt/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go @@ -20,7 +20,7 @@ var tp, te, tt, t1, tr []string var rootPersPre, echoPre, echoPersPre, timesPersPre []string var flagb1, flagb2, flagb3, flagbr, flagbp bool var flags1, flags2a, flags2b, flags3, outs string -var flagi1, flagi2, flagi3, flagir int +var flagi1, flagi2, flagi3, flagi4, flagir int var globalFlag1 bool var flagEcho, rootcalled bool var versionUsed int @@ -125,6 +125,14 @@ var cmdSubNoRun = &Command{ Long: "A long output about a subcommand without a Run function", } +var cmdCustomFlags = &Command{ + Use: "customflags [flags] -- REMOTE_COMMAND", + Short: "A command that expects flags in a custom location", + Long: "A long output about a command that expects flags in a custom location", + Run: func(cmd *Command, args []string) { + }, +} + var cmdVersion1 = &Command{ Use: "version", Short: "Print the version number", @@ -157,10 +165,12 @@ func flagInit() { cmdRootSameName.ResetFlags() cmdRootWithRun.ResetFlags() cmdSubNoRun.ResetFlags() + cmdCustomFlags.ResetFlags() cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp) cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone") cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo") cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree") + cmdCustomFlags.Flags().IntVar(&flagi4, "intfour", 456, "help message for flag intfour") cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone") cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool") cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp) @@ -180,6 +190,7 @@ func commandInit() { cmdRootSameName.ResetCommands() cmdRootWithRun.ResetCommands() cmdSubNoRun.ResetCommands() + cmdCustomFlags.ResetCommands() } func initialize() *Command { @@ -271,7 +282,7 @@ func fullTester(c *Command, input string) resulter { // Testing flag with invalid input c.SetOutput(buf) cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated) + c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated) c.SetArgs(strings.Split(input, " ")) err := c.Execute() @@ -441,6 +452,14 @@ func TestGrandChildSameName(t *testing.T) { } } +func TestUsage(t *testing.T) { + x := fullSetupTest("help") + checkResultContains(t, x, cmdRootWithRun.Use + " [flags]") + x = fullSetupTest("help customflags") + checkResultContains(t, x, cmdCustomFlags.Use) + checkResultOmits(t, x, cmdCustomFlags.Use + " [flags]") +} + func TestFlagLong(t *testing.T) { noRRSetupTest("echo --intone=13 something -- here") http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/Godeps/_workspace/src/github.com/spf13/cobra/command.go ---------------------------------------------------------------------- diff --git a/newt/Godeps/_workspace/src/github.com/spf13/cobra/command.go b/newt/Godeps/_workspace/src/github.com/spf13/cobra/command.go index ccc41c3..7671ce5 100644 --- a/newt/Godeps/_workspace/src/github.com/spf13/cobra/command.go +++ b/newt/Godeps/_workspace/src/github.com/spf13/cobra/command.go @@ -263,7 +263,7 @@ func (c *Command) UsageTemplate() string { return c.parent.UsageTemplate() } else { return `Usage:{{if .Runnable}} - {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}} + {{if .HasFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasSubCommands}} {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}} Aliases: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/jww_test.go ---------------------------------------------------------------------- diff --git a/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/jww_test.go b/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/jww_test.go index b6d118a..c405185 100644 --- a/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/jww_test.go +++ b/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/jww_test.go @@ -1,4 +1,4 @@ -// Copyright © 2014 Steve Francia <[email protected]>. +// Copyright © 2016 Steve Francia <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. @@ -6,51 +6,91 @@ package jwalterweatherman import ( - "bytes" - "github.com/stretchr/testify/assert" - "testing" + "bytes" + "github.com/stretchr/testify/assert" + "sync" + "testing" ) func TestLevels(t *testing.T) { - SetStdoutThreshold(LevelError) - assert.Equal(t, StdoutThreshold(), LevelError) - SetLogThreshold(LevelCritical) - assert.Equal(t, LogThreshold(), LevelCritical) - assert.NotEqual(t, StdoutThreshold(), LevelCritical) - SetStdoutThreshold(LevelWarn) - assert.Equal(t, StdoutThreshold(), LevelWarn) + SetStdoutThreshold(LevelError) + assert.Equal(t, StdoutThreshold(), LevelError) + SetLogThreshold(LevelCritical) + assert.Equal(t, LogThreshold(), LevelCritical) + assert.NotEqual(t, StdoutThreshold(), LevelCritical) + SetStdoutThreshold(LevelWarn) + assert.Equal(t, StdoutThreshold(), LevelWarn) } func TestDefaultLogging(t *testing.T) { - outputBuf := new(bytes.Buffer) - logBuf := new(bytes.Buffer) - LogHandle = logBuf - OutHandle = outputBuf - - SetLogThreshold(LevelWarn) - SetStdoutThreshold(LevelError) - - FATAL.Println("fatal err") - CRITICAL.Println("critical err") - ERROR.Println("an error") - WARN.Println("a warning") - INFO.Println("information") - DEBUG.Println("debugging info") - TRACE.Println("trace") - - assert.Contains(t, logBuf.String(), "fatal err") - assert.Contains(t, logBuf.String(), "critical err") - assert.Contains(t, logBuf.String(), "an error") - assert.Contains(t, logBuf.String(), "a warning") - assert.NotContains(t, logBuf.String(), "information") - assert.NotContains(t, logBuf.String(), "debugging info") - assert.NotContains(t, logBuf.String(), "trace") - - assert.Contains(t, outputBuf.String(), "fatal err") - assert.Contains(t, outputBuf.String(), "critical err") - assert.Contains(t, outputBuf.String(), "an error") - assert.NotContains(t, outputBuf.String(), "a warning") - assert.NotContains(t, outputBuf.String(), "information") - assert.NotContains(t, outputBuf.String(), "debugging info") - assert.NotContains(t, outputBuf.String(), "trace") + outputBuf := new(bytes.Buffer) + logBuf := new(bytes.Buffer) + LogHandle = logBuf + OutHandle = outputBuf + + SetLogThreshold(LevelWarn) + SetStdoutThreshold(LevelError) + + FATAL.Println("fatal err") + CRITICAL.Println("critical err") + ERROR.Println("an error") + WARN.Println("a warning") + INFO.Println("information") + DEBUG.Println("debugging info") + TRACE.Println("trace") + + assert.Contains(t, logBuf.String(), "fatal err") + assert.Contains(t, logBuf.String(), "critical err") + assert.Contains(t, logBuf.String(), "an error") + assert.Contains(t, logBuf.String(), "a warning") + assert.NotContains(t, logBuf.String(), "information") + assert.NotContains(t, logBuf.String(), "debugging info") + assert.NotContains(t, logBuf.String(), "trace") + + assert.Contains(t, outputBuf.String(), "fatal err") + assert.Contains(t, outputBuf.String(), "critical err") + assert.Contains(t, outputBuf.String(), "an error") + assert.NotContains(t, outputBuf.String(), "a warning") + assert.NotContains(t, outputBuf.String(), "information") + assert.NotContains(t, outputBuf.String(), "debugging info") + assert.NotContains(t, outputBuf.String(), "trace") +} + +func TestLogCounter(t *testing.T) { + ResetLogCounters() + + FATAL.Println("fatal err") + CRITICAL.Println("critical err") + WARN.Println("a warning") + WARN.Println("another warning") + INFO.Println("information") + DEBUG.Println("debugging info") + TRACE.Println("trace") + + wg := &sync.WaitGroup{} + + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 10; j++ { + ERROR.Println("error", j) + // check for data races + assert.True(t, LogCountForLevel(LevelError) > uint64(j)) + assert.True(t, LogCountForLevelsGreaterThanorEqualTo(LevelError) > uint64(j)) + } + }() + + } + + wg.Wait() + + assert.Equal(t, uint64(1), LogCountForLevel(LevelFatal)) + assert.Equal(t, uint64(1), LogCountForLevel(LevelCritical)) + assert.Equal(t, uint64(2), LogCountForLevel(LevelWarn)) + assert.Equal(t, uint64(1), LogCountForLevel(LevelInfo)) + assert.Equal(t, uint64(1), LogCountForLevel(LevelDebug)) + assert.Equal(t, uint64(1), LogCountForLevel(LevelTrace)) + assert.Equal(t, uint64(100), LogCountForLevel(LevelError)) + assert.Equal(t, uint64(102), LogCountForLevelsGreaterThanorEqualTo(LevelError)) } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go ---------------------------------------------------------------------- diff --git a/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go b/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go index e7abe01..b64ed46 100644 --- a/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go +++ b/newt/Godeps/_workspace/src/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go @@ -1,4 +1,4 @@ -// Copyright © 2014 Steve Francia <[email protected]>. +// Copyright © 2016 Steve Francia <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. @@ -11,6 +11,7 @@ import ( "io/ioutil" "log" "os" + "sync/atomic" ) // Level describes the chosen log level between @@ -18,10 +19,33 @@ import ( type Level int type NotePad struct { - Handle io.Writer - Level Level - Prefix string - Logger **log.Logger + Handle io.Writer + Level Level + Prefix string + Logger **log.Logger + counter uint64 +} + +func (n *NotePad) incr() { + atomic.AddUint64(&n.counter, 1) +} + +func (n *NotePad) resetCounter() { + atomic.StoreUint64(&n.counter, 0) +} + +func (n *NotePad) getCount() uint64 { + return atomic.LoadUint64(&n.counter) +} + +type countingWriter struct { + incrFunc func() +} + +func (cw *countingWriter) Write(p []byte) (n int, err error) { + cw.incrFunc() + + return 0, nil } // Feedback is special. It writes plainly to the output while @@ -65,15 +89,18 @@ var ( fatal *NotePad = &NotePad{Level: LevelFatal, Handle: os.Stdout, Logger: &FATAL, Prefix: "FATAL: "} logThreshold Level = DefaultLogThreshold outputThreshold Level = DefaultStdoutThreshold +) - DATE = log.Ldate - TIME = log.Ltime - SFILE = log.Lshortfile - LFILE = log.Llongfile - MSEC = log.Lmicroseconds - logFlags = DATE | TIME | SFILE +const ( + DATE = log.Ldate + TIME = log.Ltime + SFILE = log.Lshortfile + LFILE = log.Llongfile + MSEC = log.Lmicroseconds ) +var logFlags = DATE | TIME | SFILE + func init() { SetStdoutThreshold(DefaultStdoutThreshold) } @@ -98,6 +125,7 @@ func initialize() { } for _, n := range NotePads { + n.Handle = io.MultiWriter(n.Handle, &countingWriter{n.incr}) *n.Logger = log.New(n.Handle, n.Prefix, logFlags) } @@ -109,6 +137,7 @@ func initialize() { // Set the log Flags (Available flag: DATE, TIME, SFILE, LFILE and MSEC) func SetLogFlag(flags int) { logFlags = flags + initialize() } // Level returns the current global log threshold. @@ -173,6 +202,35 @@ func UseTempLogFile(prefix string) { initialize() } +// LogCountForLevel returns the number of log invocations for a given level. +func LogCountForLevel(l Level) uint64 { + for _, np := range NotePads { + if np.Level == l { + return np.getCount() + } + } + return 0 +} + +// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations +// greater than or equal to a given level threshold. +func LogCountForLevelsGreaterThanorEqualTo(threshold Level) uint64 { + var cnt uint64 + for _, np := range NotePads { + if np.Level >= threshold { + cnt += np.getCount() + } + } + return cnt +} + +// ResetLogCounters resets the invocation counters for all levels. +func ResetLogCounters() { + for _, np := range NotePads { + np.resetCounter() + } +} + // Disables logging for the entire JWW system func DiscardLogging() { LogHandle = ioutil.Discard http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/builder/buildpackage.go ---------------------------------------------------------------------- diff --git a/newt/builder/buildpackage.go b/newt/builder/buildpackage.go index 9d0ecaa..dcfffcb 100644 --- a/newt/builder/buildpackage.go +++ b/newt/builder/buildpackage.go @@ -21,9 +21,10 @@ package builder import ( "fmt" - "log" "path/filepath" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/newt/newtutil" "mynewt.apache.org/newt/newt/pkg" "mynewt.apache.org/newt/newt/project" @@ -163,7 +164,7 @@ func (bpkg *BuildPackage) loadFeatures(b *Builder) (map[string]bool, bool) { if !ok { b.AddFeature(nfeature) foundNewFeature = true - log.Printf("[DEBUG] Detected new feature: %s (%s)", nfeature, + log.Debugf("Detected new feature: %s (%s)", nfeature, bpkg.Name()) } } @@ -190,7 +191,7 @@ func (bpkg *BuildPackage) satisfyReqApi(b *Builder, reqApi string) bool { // This package now has a new unresolved dependency. bpkg.depsResolved = false - log.Printf("[DEBUG] API requirement satisfied; pkg=%s API=(%s, %s)", + log.Debugf("API requirement satisfied; pkg=%s API=(%s, %s)", bpkg.Name(), reqApi, dep.String()) return true http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/builder/buildutil.go ---------------------------------------------------------------------- diff --git a/newt/builder/buildutil.go b/newt/builder/buildutil.go index be4b180..2834e8b 100644 --- a/newt/builder/buildutil.go +++ b/newt/builder/buildutil.go @@ -21,10 +21,11 @@ package builder import ( "bytes" - "log" "path/filepath" "sort" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/newt/pkg" "mynewt.apache.org/newt/newt/project" "mynewt.apache.org/newt/util" @@ -156,7 +157,7 @@ func (b bpkgSorter) Less(i, j int) bool { func (b *Builder) logDepInfo() { // Log feature set. - log.Printf("[DEBUG] Feature set: [" + b.FeatureString() + "]") + log.Debugf("Feature set: [" + b.FeatureString() + "]") // Log API set. apis := make([]string, 0, len(b.apis)) @@ -165,10 +166,10 @@ func (b *Builder) logDepInfo() { } sort.Strings(apis) - log.Printf("[DEBUG] API set:") + log.Debugf("API set:") for _, api := range apis { bpkg := b.apis[api] - log.Printf("[DEBUG] * " + api + " (" + bpkg.Name() + ")") + log.Debugf(" * " + api + " (" + bpkg.Name() + ")") } // Log dependency graph. @@ -180,7 +181,7 @@ func (b *Builder) logDepInfo() { } sort.Sort(bpkgSorter) - log.Printf("[DEBUG] Dependency graph:") + log.Debugf("Dependency graph:") var buffer bytes.Buffer for _, bpkg := range bpkgSorter.bpkgs { buffer.Reset() @@ -190,7 +191,7 @@ func (b *Builder) logDepInfo() { } buffer.WriteString(dep.String()) } - log.Printf("[DEBUG] * " + bpkg.Name() + " [" + + log.Debugf(" * " + bpkg.Name() + " [" + buffer.String() + "]") } } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/cli/util.go ---------------------------------------------------------------------- diff --git a/newt/cli/util.go b/newt/cli/util.go index fba262a..4270ea1 100644 --- a/newt/cli/util.go +++ b/newt/cli/util.go @@ -22,13 +22,14 @@ package cli import ( "bytes" "fmt" - "log" "os" "path/filepath" "regexp" "strings" + log "github.com/Sirupsen/logrus" "github.com/spf13/cobra" + "mynewt.apache.org/newt/newt/newtutil" "mynewt.apache.org/newt/newt/pkg" "mynewt.apache.org/newt/newt/project" @@ -42,7 +43,7 @@ const TARGET_DEFAULT_DIR string = "targets" func NewtUsage(cmd *cobra.Command, err error) { if err != nil { sErr := err.(*util.NewtError) - log.Printf("[DEBUG] %s", sErr.StackTrace) + log.Debugf("%s", sErr.StackTrace) fmt.Fprintf(os.Stderr, "Error: %s\n", sErr.Text) } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/downloader/downloader.go ---------------------------------------------------------------------- diff --git a/newt/downloader/downloader.go b/newt/downloader/downloader.go index 5b755fe..1a816d5 100644 --- a/newt/downloader/downloader.go +++ b/newt/downloader/downloader.go @@ -23,12 +23,13 @@ import ( "fmt" "io" "io/ioutil" - "log" "net/http" "os" "os/exec" "strings" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/util" ) @@ -66,7 +67,7 @@ func (gd *GithubDownloader) FetchFile(name string, dest string) error { fmtStr := "https://raw.githubusercontent.com/%s/%s/%s/%s" url := fmt.Sprintf(fmtStr, gd.User, gd.Repo, gd.Branch(), name) - log.Printf("[DEBUG] Fetching file %s (url: %s) to %s", name, url, dest) + log.Debugf("Fetching file %s (url: %s) to %s", name, url, dest) rsp, err := http.Get(url) if err != nil { http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/image/image.go ---------------------------------------------------------------------- diff --git a/newt/image/image.go b/newt/image/image.go index cb7c36d..5ab749a 100644 --- a/newt/image/image.go +++ b/newt/image/image.go @@ -26,7 +26,6 @@ import ( "encoding/json" "fmt" "io" - "log" "os" "path/filepath" "sort" @@ -34,6 +33,8 @@ import ( "strings" "time" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/newt/builder" "mynewt.apache.org/newt/newt/target" "mynewt.apache.org/newt/util" @@ -168,7 +169,7 @@ func (image *Image) SetVersion(versStr string) error { image.version.Minor = uint8(minor) image.version.Rev = uint16(rev) image.version.BuildNum = uint32(buildNum) - log.Printf("[VERBOSE] Assigning version number %d.%d.%d.%d\n", + log.Debugf("Assigning version number %d.%d.%d.%d\n", image.version.Major, image.version.Minor, image.version.Rev, image.version.BuildNum) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/newt.go ---------------------------------------------------------------------- diff --git a/newt/newt.go b/newt/newt.go index 13516bd..d56fc9b 100644 --- a/newt/newt.go +++ b/newt/newt.go @@ -21,16 +21,16 @@ package main import ( "fmt" - "strings" + + log "github.com/Sirupsen/logrus" + "github.com/spf13/cobra" "mynewt.apache.org/newt/newt/cli" "mynewt.apache.org/newt/util" - - "github.com/spf13/cobra" ) var NewtVersion string = "0.8.0" -var NewtLogLevel string = "" +var NewtLogLevel log.Level var newtSilent bool var newtQuiet bool var newtVerbose bool @@ -52,14 +52,13 @@ func newtCmd() *cobra.Command { newtHelpEx += " For help on <command-name>. If not specified, " + "print this message." + logLevelStr := "" newtCmd := &cobra.Command{ Use: "newt", Short: "Newt is a tool to help you compose and build your own OS", Long: newtHelpText, Example: newtHelpEx, PersistentPreRun: func(cmd *cobra.Command, args []string) { - NewtLogLevel = strings.ToUpper(NewtLogLevel) - verbosity := util.VERBOSITY_DEFAULT if newtSilent { verbosity = util.VERBOSITY_SILENT @@ -69,7 +68,13 @@ func newtCmd() *cobra.Command { verbosity = util.VERBOSITY_VERBOSE } - err := util.Init(NewtLogLevel, newtLogFile, verbosity) + var err error + NewtLogLevel, err = log.ParseLevel(logLevelStr) + if err != nil { + cli.NewtUsage(nil, util.NewNewtError(err.Error())) + } + + err = util.Init(NewtLogLevel, newtLogFile, verbosity) if err != nil { cli.NewtUsage(nil, err) } @@ -85,7 +90,7 @@ func newtCmd() *cobra.Command { "Be quiet; only display error output.") newtCmd.PersistentFlags().BoolVarP(&newtSilent, "silent", "s", false, "Be silent; don't output anything.") - newtCmd.PersistentFlags().StringVarP(&NewtLogLevel, "loglevel", "l", + newtCmd.PersistentFlags().StringVarP(&logLevelStr, "loglevel", "l", "WARN", "Log level, defaults to WARN.") newtCmd.PersistentFlags().StringVarP(&newtLogFile, "outfile", "o", "", "Filename to tee log output to") http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/pkg/localpackage.go ---------------------------------------------------------------------- diff --git a/newt/pkg/localpackage.go b/newt/pkg/localpackage.go index d4e0664..b776f9d 100644 --- a/newt/pkg/localpackage.go +++ b/newt/pkg/localpackage.go @@ -24,11 +24,12 @@ import ( "crypto/sha1" "fmt" "io/ioutil" - "log" "os" "path/filepath" "strings" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/newt/interfaces" "mynewt.apache.org/newt/newt/newtutil" "mynewt.apache.org/newt/newt/repo" @@ -287,7 +288,7 @@ func (pkg *LocalPackage) Save() error { // package func (pkg *LocalPackage) Load() error { // Load configuration - log.Printf("[DEBUG] Loading configuration for package %s", pkg.basePath) + log.Debugf("Loading configuration for package %s", pkg.basePath) v, err := util.ReadConfig(pkg.basePath, strings.TrimSuffix(PACKAGE_FILE_NAME, ".yml")) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/project/project.go ---------------------------------------------------------------------- diff --git a/newt/project/project.go b/newt/project/project.go index f8b079e..ea49d02 100644 --- a/newt/project/project.go +++ b/newt/project/project.go @@ -22,11 +22,12 @@ package project import ( "bufio" "fmt" - "log" "os" "path" "strings" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/newt/downloader" "mynewt.apache.org/newt/newt/interfaces" "mynewt.apache.org/newt/newt/pkg" @@ -397,7 +398,7 @@ func (proj *Project) loadRepo(rname string, v *viper.Viper) error { proj.localRepo.AddDependency(rd) - log.Printf("[VERBOSE] Loaded repository %s (type: %s, user: %s, repo: %s)", rname, + log.Debugf("Loaded repository %s (type: %s, user: %s, repo: %s)", rname, repoVars["type"], repoVars["user"], repoVars["repo"]) proj.repos[r.Name()] = r @@ -479,9 +480,9 @@ func findProjectDir(dir string) (string, error) { for { projFile := path.Clean(dir) + "/" + PROJECT_FILE_NAME - log.Printf("[DEBUG] Searching for project file %s", projFile) + log.Debugf("Searching for project file %s", projFile) if util.NodeExist(projFile) { - log.Printf("[INFO] Project file found at %s", projFile) + log.Infof("Project file found at %s", projFile) if firstProjectDir == "" { firstProjectDir = dir } else { @@ -510,7 +511,7 @@ func (proj *Project) loadPackageList() error { // packages / store them in the project package list. repos := proj.Repos() for name, repo := range repos { - log.Printf("[VERBOSE] Loading packages in repository %s", repo.Path()) + log.Debugf("Loading packages in repository %s", repo.Path()) list, err := pkg.ReadLocalPackages(repo, repo.Path(), proj.PackageSearchDirs()) if err != nil { http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/repo/repo.go ---------------------------------------------------------------------- diff --git a/newt/repo/repo.go b/newt/repo/repo.go index 50b83ab..9b3fada 100644 --- a/newt/repo/repo.go +++ b/newt/repo/repo.go @@ -21,16 +21,16 @@ package repo import ( "fmt" - "log" "os" "path/filepath" "strings" - "mynewt.apache.org/newt/viper" + log "github.com/Sirupsen/logrus" "mynewt.apache.org/newt/newt/downloader" "mynewt.apache.org/newt/newt/interfaces" "mynewt.apache.org/newt/util" + "mynewt.apache.org/newt/viper" ) const REPO_NAME_LOCAL = "local" @@ -98,7 +98,7 @@ func CheckDeps(upgrade bool, checkRepos map[string]*Repo) error { return util.NewNewtError(fmt.Sprintf("No "+ "matching version for dependent repository %s", rd.name)) } - log.Printf("[DEBUG] Dependency for %s: %s (%s)", checkRepo.Name(), rd.Name(), vers.String()) + log.Debugf("Dependency for %s: %s (%s)", checkRepo.Name(), rd.Name(), vers.String()) _, ok = depArray[rd.Name()] if !ok { @@ -137,9 +137,9 @@ func (rd *RepoDesc) MatchVersion(searchVers *Version) (string, *Version, bool) { func (rd *RepoDesc) Match(r *Repo) (string, *Version, bool) { for vers, branch := range rd.vers { - log.Printf("[DEBUG] Repository version requires for %s are %s\n", r.Name(), r.VersionRequirements()) + log.Debugf("Repository version requires for %s are %s\n", r.Name(), r.VersionRequirements()) if vers.SatisfiesVersion(r.VersionRequirements()) { - log.Printf("[DEBUG] Found matching version %s for repo %s", + log.Debugf("Found matching version %s for repo %s", vers.String(), r.Name()) if vers.Stability() != VERSION_STABILITY_NONE { // Load the branch as a version, and search for it @@ -156,7 +156,7 @@ func (rd *RepoDesc) Match(r *Repo) (string, *Version, bool) { if !ok { return "", nil, false } - log.Printf("[DEBUG] Founding matching version %s for search version %s, related branch is %s\n", + log.Debugf("Founding matching version %s for search version %s, related branch is %s\n", vers, searchVers, branch) } @@ -201,7 +201,7 @@ func (rd *RepoDesc) Init(name string, versBranchMap map[string]string) error { rd.vers = map[*Version]string{} for versStr, branch := range versBranchMap { - log.Printf("[DEBUG] Printing version %s for remote repo %s", versStr, name) + log.Debugf("Printing version %s for remote repo %s", versStr, name) vers, err := LoadVersion(versStr) if err != nil { return err http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newt/toolchain/compiler.go ---------------------------------------------------------------------- diff --git a/newt/toolchain/compiler.go b/newt/toolchain/compiler.go index f67c5c2..f92ebc1 100644 --- a/newt/toolchain/compiler.go +++ b/newt/toolchain/compiler.go @@ -21,7 +21,6 @@ package toolchain import ( "io/ioutil" - "log" "os" "path" "path/filepath" @@ -30,6 +29,8 @@ import ( "strings" "time" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/newt/newtutil" "mynewt.apache.org/newt/util" "mynewt.apache.org/newt/viper" @@ -162,7 +163,7 @@ func (c *Compiler) load(compilerDir string, buildProfile string) error { buildProfile, runtime.GOOS) } - log.Printf("[INFO] ccPath = %s, arPath = %s, flags = %s", c.ccPath, + log.Infof("ccPath = %s, arPath = %s, flags = %s", c.ccPath, c.arPath, c.info.Cflags) return nil @@ -369,7 +370,7 @@ func (c *Compiler) CompileC() error { return err } - log.Printf("[INFO] Compiling C if outdated (%s/*.c) %s", wd, + log.Infof("Compiling C if outdated (%s/*.c) %s", wd, strings.Join(files, " ")) for _, file := range files { file = filepath.ToSlash(file) @@ -403,7 +404,7 @@ func (c *Compiler) CompileAs() error { return err } - log.Printf("[INFO] Compiling assembly if outdated (%s/*.s) %s", wd, + log.Infof("Compiling assembly if outdated (%s/*.s) %s", wd, strings.Join(files, " ")) for _, file := range files { compileRequired, err := c.depTracker.CompileRequired(file, http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newtmgr/cli/commands.go ---------------------------------------------------------------------- diff --git a/newtmgr/cli/commands.go b/newtmgr/cli/commands.go index 1324b82..5a4f090 100644 --- a/newtmgr/cli/commands.go +++ b/newtmgr/cli/commands.go @@ -20,32 +20,27 @@ package cli import ( - "log" - "os" - - "github.com/hashicorp/logutils" + log "github.com/Sirupsen/logrus" "github.com/spf13/cobra" + + "mynewt.apache.org/newt/util" ) var ConnProfileName string - -var LogLevel string = "WARN" - -func SetupLog() { - filter := &logutils.LevelFilter{ - Levels: []logutils.LogLevel{"DEBUG", "VERBOSE", "INFO", - "WARN", "ERROR"}, - MinLevel: logutils.LogLevel(LogLevel), - Writer: os.Stderr, - } - - log.SetOutput(filter) -} +var NewtmgrLogLevel log.Level func Commands() *cobra.Command { + logLevelStr := "" nmCmd := &cobra.Command{ Use: "newtmgr", Short: "Newtmgr helps you manage remote instances of the Mynewt OS.", + PersistentPreRun: func(cmd *cobra.Command, args []string) { + NewtmgrLogLevel, err := log.ParseLevel(logLevelStr) + err = util.Init(NewtmgrLogLevel, "", util.VERBOSITY_DEFAULT) + if err != nil { + nmUsage(nil, err) + } + }, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, @@ -54,7 +49,7 @@ func Commands() *cobra.Command { nmCmd.PersistentFlags().StringVarP(&ConnProfileName, "conn", "c", "", "connection profile to use.") - nmCmd.PersistentFlags().StringVarP(&LogLevel, "loglevel", "l", "", + nmCmd.PersistentFlags().StringVarP(&logLevelStr, "loglevel", "l", "", "log level to use (default WARN.)") nmCmd.AddCommand(connProfileCmd()) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newtmgr/config/connprofile.go ---------------------------------------------------------------------- diff --git a/newtmgr/config/connprofile.go b/newtmgr/config/connprofile.go index 6b32c02..0ddf61f 100644 --- a/newtmgr/config/connprofile.go +++ b/newtmgr/config/connprofile.go @@ -20,9 +20,9 @@ package config import ( - "log" - + log "github.com/Sirupsen/logrus" "github.com/mitchellh/go-homedir" + "mynewt.apache.org/newt/util" ) @@ -69,7 +69,7 @@ func (cpm *ConnProfileMgr) Init() error { } func (cpm *ConnProfileMgr) GetConnProfileList() ([]*ConnProfile, error) { - log.Printf("[DEBUG] Getting list of connection profiles") + log.Debugf("Getting list of connection profiles") cpMap, err := cpm.cDb.GetSect("conn_profile_list") if err != nil { return nil, err http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newtmgr/newtmgr.go ---------------------------------------------------------------------- diff --git a/newtmgr/newtmgr.go b/newtmgr/newtmgr.go index 3173ee7..eb92a8b 100644 --- a/newtmgr/newtmgr.go +++ b/newtmgr/newtmgr.go @@ -22,6 +22,5 @@ package main import "mynewt.apache.org/newt/newtmgr/cli" func main() { - cli.SetupLog() cli.Commands().Execute() } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newtmgr/protocol/cmdrunner.go ---------------------------------------------------------------------- diff --git a/newtmgr/protocol/cmdrunner.go b/newtmgr/protocol/cmdrunner.go index 2f76188..6ecc8ca 100644 --- a/newtmgr/protocol/cmdrunner.go +++ b/newtmgr/protocol/cmdrunner.go @@ -20,7 +20,7 @@ package protocol import ( - "log" + log "github.com/Sirupsen/logrus" "mynewt.apache.org/newt/newtmgr/transport" ) @@ -52,7 +52,7 @@ func (cr *CmdRunner) ReadResp() (*NmgrReq, error) { func (cr *CmdRunner) WriteReq(nmr *NmgrReq) error { data := []byte{} - log.Printf("[DEBUG] Writing netmgr request %s", nmr) + log.Debugf("Writing netmgr request %s", nmr) data, err := nmr.SerializeRequest(data) if err != nil { http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newtmgr/protocol/nmgr.go ---------------------------------------------------------------------- diff --git a/newtmgr/protocol/nmgr.go b/newtmgr/protocol/nmgr.go index 4cb8c0d..8fadb46 100644 --- a/newtmgr/protocol/nmgr.go +++ b/newtmgr/protocol/nmgr.go @@ -22,7 +22,8 @@ package protocol import ( "encoding/binary" "fmt" - "log" + + log "github.com/Sirupsen/logrus" "mynewt.apache.org/newt/util" ) @@ -77,7 +78,7 @@ func DeserializeNmgrReq(data []byte) (*NmgrReq, error) { } func (nmr *NmgrReq) SerializeRequest(data []byte) ([]byte, error) { - log.Printf("[DEBUG] Serializing request %s into buffer %s", nmr, data) + log.Debugf("Serializing request %s into buffer %s", nmr, data) u16b := make([]byte, 2) http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/newtmgr/transport/connserial.go ---------------------------------------------------------------------- diff --git a/newtmgr/transport/connserial.go b/newtmgr/transport/connserial.go index 9e03343..fe22fd2 100644 --- a/newtmgr/transport/connserial.go +++ b/newtmgr/transport/connserial.go @@ -24,11 +24,12 @@ import ( "encoding/base64" "encoding/binary" "fmt" - "log" + + log "github.com/Sirupsen/logrus" + "github.com/tarm/serial" "mynewt.apache.org/newt/newtmgr/config" "mynewt.apache.org/newt/util" - "github.com/tarm/serial" ) type ConnSerial struct { @@ -115,7 +116,7 @@ func (cs *ConnSerial) ReadPacket() (*Packet, error) { } func (cs *ConnSerial) writeData(bytes []byte) { - log.Printf("[DEBUG] Writing %b to data channel", bytes) + log.Debugf("Writing %b to data channel", bytes) cs.serialChannel.Write(bytes) } http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/util/cfgdb.go ---------------------------------------------------------------------- diff --git a/util/cfgdb.go b/util/cfgdb.go index ba169c1..e333c6e 100644 --- a/util/cfgdb.go +++ b/util/cfgdb.go @@ -22,8 +22,8 @@ package util import ( "database/sql" "fmt" - "log" + log "github.com/Sirupsen/logrus" _ "github.com/mattn/go-sqlite3" ) @@ -76,7 +76,7 @@ func (c *CfgDb) Init(prefix string, dbPath string) error { } c.db = db - log.Printf("[DEBUG] Reading config from %s for %s", dbPath, prefix) + log.Debugf("Reading config from %s for %s", dbPath, prefix) rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s_cfg", prefix)) if err != nil { @@ -93,7 +93,7 @@ func (c *CfgDb) Init(prefix string, dbPath string) error { return NewNewtError(err.Error()) } - log.Printf("[DEBUG] Setting sect %s, key %s to val %s", cName.String, + log.Debugf("Setting sect %s, key %s to val %s", cName.String, cKey.String, cVal.String) if _, ok := c.Config[cName.String]; !ok { @@ -152,7 +152,7 @@ func (c *CfgDb) GetSect(sect string) (map[string]string, error) { } func (c *CfgDb) DeleteSect(sect string) error { - log.Printf("[DEBUG] Deleting sect %s", sect) + log.Debugf("Deleting sect %s", sect) tx, err := c.db.Begin() if err != nil { @@ -174,10 +174,10 @@ func (c *CfgDb) DeleteSect(sect string) error { tx.Commit() if naffected, err := r.RowsAffected(); naffected > 0 && err == nil { - log.Printf("[DEBUG] Successfully deleted sect %s from db %s", + log.Debugf("Successfully deleted sect %s from db %s", sect, c.DbPath) } else { - log.Printf("[DEBUG] Sect %s not found in db %s. Delete "+ + log.Debugf("Sect %s not found in db %s. Delete "+ "successful", sect, c.DbPath) } @@ -185,7 +185,7 @@ func (c *CfgDb) DeleteSect(sect string) error { } func (c *CfgDb) DeleteKey(sect string, key string) error { - log.Printf("[DEBUG] Deleting sect %s, key %s", sect, key) + log.Debugf("Deleting sect %s, key %s", sect, key) tx, err := c.db.Begin() if err != nil { @@ -207,10 +207,10 @@ func (c *CfgDb) DeleteKey(sect string, key string) error { tx.Commit() if naffected, err := r.RowsAffected(); naffected > 0 && err == nil { - log.Printf("[DEBUG] Successfully deleted sect %s, key %s from db %s", + log.Debugf("Successfully deleted sect %s, key %s from db %s", sect, key, c.DbPath) } else { - log.Printf("[DEBUG] Sect %s, key %s not found in db %s. Delete "+ + log.Debugf("Sect %s, key %s not found in db %s. Delete "+ "successful", sect, key, c.DbPath) } @@ -219,12 +219,12 @@ func (c *CfgDb) DeleteKey(sect string, key string) error { func (c *CfgDb) SetKey(sect string, key string, val string) error { if _, ok := c.Config[sect]; !ok { - log.Printf("[DEBUG] Section %s doesn't exist, creating it!", sect) + log.Debugf("Section %s doesn't exist, creating it!", sect) c.Config[sect] = make(map[string]string) } c.Config[sect][key] = val - log.Printf("[DEBUG] Storing value %s in section %s, key %s", + log.Debugf("Storing value %s in section %s, key %s", val, sect, key) tx, err := c.db.Begin() @@ -247,7 +247,7 @@ func (c *CfgDb) SetKey(sect string, key string, val string) error { // If update succeeded, then exit out. if naffected, err := r.RowsAffected(); naffected > 0 && err == nil { tx.Commit() - log.Printf("[DEBUG] Sect %s, key %s successfully updated to %s", + log.Debugf("Sect %s, key %s successfully updated to %s", sect, key, val) return nil } @@ -266,7 +266,7 @@ func (c *CfgDb) SetKey(sect string, key string, val string) error { tx.Commit() - log.Printf("[DEBUG] Section %s, key %s successfully created. Value set"+ + log.Debugf("Section %s, key %s successfully created. Value set"+ "to %s", sect, key, val) return nil http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4ae9684f/util/util.go ---------------------------------------------------------------------- diff --git a/util/util.go b/util/util.go index 22e8a90..d8a1a9a 100644 --- a/util/util.go +++ b/util/util.go @@ -21,10 +21,10 @@ package util import ( "bufio" + "bytes" "fmt" "io" "io/ioutil" - "log" "os" "os/exec" "os/signal" @@ -36,7 +36,8 @@ import ( "syscall" "time" - "github.com/hashicorp/logutils" + log "github.com/Sirupsen/logrus" + "mynewt.apache.org/newt/viper" ) @@ -165,7 +166,24 @@ func Max(x, y int) int { return y } -func initLog(level string, logFilename string) error { +type logFormatter struct{} + +func (f *logFormatter) Format(entry *log.Entry) ([]byte, error) { + // 2016/03/16 12:50:47 [DEBUG] + + b := &bytes.Buffer{} + + b.WriteString(entry.Time.Format("2006/01/02 15:04:05 ")) + b.WriteString("[" + strings.ToUpper(entry.Level.String()) + "] ") + b.WriteString(entry.Message) + b.WriteByte('\n') + + return b.Bytes(), nil +} + +func initLog(level log.Level, logFilename string) error { + log.SetLevel(level) + var writer io.Writer if logFilename == "" { writer = os.Stderr @@ -179,24 +197,14 @@ func initLog(level string, logFilename string) error { writer = io.MultiWriter(os.Stderr, logFile) } - filter := &logutils.LevelFilter{ - Levels: []logutils.LogLevel{"DEBUG", "VERBOSE", "INFO", - "WARN", "ERROR"}, - MinLevel: logutils.LogLevel(level), - Writer: writer, - } - - log.SetOutput(filter) + log.SetOutput(writer) + log.SetFormatter(&logFormatter{}) return nil } // Initialize the util module -func Init(logLevel string, logFile string, verbosity int) error { - if logLevel == "" { - logLevel = "WARN" - } - +func Init(logLevel log.Level, logFile string, verbosity int) error { // Configure logging twice. First just configure the filter for stderr; // second configure the logfile if there is one. This needs to happen in // two steps so that the log level is configured prior to the attempt to @@ -272,11 +280,11 @@ func DescendantDirsOfParent(rootPath string, parentName string, fullPath bool) ( // Execute the command specified by cmdStr on the shell and return results func ShellCommand(cmdStr string) ([]byte, error) { - log.Print("[VERBOSE] " + cmdStr) + log.Debug(cmdStr) cmd := exec.Command("sh", "-c", cmdStr) o, err := cmd.CombinedOutput() - log.Print("[VERBOSE] o=" + string(o)) + log.Debugf("o=%s", string(o)) if err != nil { return o, NewNewtError(err.Error()) } else {
