From e3c279f97b35b9b67e8296b4e27026bef40f8e30 Mon Sep 17 00:00:00 2001 From: LE Manh Cuong Date: Sat, 10 Aug 2019 01:24:54 +0700 Subject: [PATCH] Use logrus import without alias Also add some comments to keep linter silent. Closes #1016 --- api/server.go | 14 +++--- api/server_test.go | 13 +++--- cmd/cloud.go | 8 ++-- cmd/config.go | 23 +++++----- cmd/config_consolidation_test.go | 21 ++++----- cmd/root.go | 29 ++++++------ cmd/run.go | 37 ++++++++-------- core/engine.go | 19 ++++---- core/engine_test.go | 13 +++--- core/local/local.go | 23 +++++----- js/compiler/compiler.go | 6 +-- js/console.go | 30 ++++++------- js/console_test.go | 54 +++++++++++------------ js/initcontext_test.go | 15 ++++--- js/modules/k6/html/gen/gen_elements.go | 14 +++--- js/runner.go | 17 +++---- lib/executor.go | 9 ++-- lib/netext/httpext/httpdebug_transport.go | 6 +-- lib/netext/httpext/request.go | 7 +-- lib/state.go | 7 +-- lib/testutils/logrus_hook.go | 16 +++---- loader/loader.go | 12 ++--- stats/cloud/collector.go | 27 ++++++------ stats/dummy/collector.go | 5 ++- stats/influxdb/collector.go | 19 ++++---- stats/json/collector.go | 15 ++++--- stats/kafka/collector.go | 17 +++---- stats/statsd/common/collector.go | 7 +-- 28 files changed, 253 insertions(+), 230 deletions(-) diff --git a/api/server.go b/api/server.go index cf54cc78f77..e37dcd05f78 100644 --- a/api/server.go +++ b/api/server.go @@ -24,11 +24,12 @@ import ( "fmt" "net/http" + "github.com/sirupsen/logrus" + "github.com/urfave/negroni" + "github.com/loadimpact/k6/api/common" - "github.com/loadimpact/k6/api/v1" + v1 "github.com/loadimpact/k6/api/v1" "github.com/loadimpact/k6/core" - log "github.com/sirupsen/logrus" - "github.com/urfave/negroni" ) func NewHandler() http.Handler { @@ -45,13 +46,14 @@ func ListenAndServe(addr string, engine *core.Engine) error { n := negroni.New() n.Use(negroni.NewRecovery()) n.UseFunc(WithEngine(engine)) - n.UseFunc(NewLogger(log.StandardLogger())) + n.UseFunc(NewLogger(logrus.StandardLogger())) n.UseHandler(mux) return http.ListenAndServe(addr, n) } -func NewLogger(l *log.Logger) negroni.HandlerFunc { +// NewLogger returns the middleware which logs response status for request. +func NewLogger(l *logrus.Logger) negroni.HandlerFunc { return func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { next(rw, r) @@ -71,7 +73,7 @@ func HandlePing() http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.Header().Add("Content-Type", "text/plain; charset=utf-8") if _, err := fmt.Fprint(rw, "ok"); err != nil { - log.WithError(err).Error("Error while printing ok") + logrus.WithError(err).Error("Error while printing ok") } }) } diff --git a/api/server_test.go b/api/server_test.go index f83010497b5..c634af19183 100644 --- a/api/server_test.go +++ b/api/server_test.go @@ -26,13 +26,14 @@ import ( "net/http/httptest" "testing" - "github.com/loadimpact/k6/api/common" - "github.com/loadimpact/k6/core" - "github.com/loadimpact/k6/lib" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" logtest "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" "github.com/urfave/negroni" + + "github.com/loadimpact/k6/api/common" + "github.com/loadimpact/k6/core" + "github.com/loadimpact/k6/lib" ) func testHTTPHandler(rw http.ResponseWriter, r *http.Request) { @@ -51,7 +52,7 @@ func TestLogger(t *testing.T) { r := httptest.NewRequest(method, "http://example.com"+path, nil) l, hook := logtest.NewNullLogger() - l.Level = log.DebugLevel + l.Level = logrus.DebugLevel NewLogger(l)(negroni.NewResponseWriter(rw), r, testHTTPHandler) res := rw.Result() @@ -63,7 +64,7 @@ func TestLogger(t *testing.T) { } e := hook.LastEntry() - assert.Equal(t, log.DebugLevel, e.Level) + assert.Equal(t, logrus.DebugLevel, e.Level) assert.Equal(t, fmt.Sprintf("%s %s", method, path), e.Message) assert.Equal(t, http.StatusOK, e.Data["status"]) }) diff --git a/cmd/cloud.go b/cmd/cloud.go index 7fdcd48686c..054c194bd40 100644 --- a/cmd/cloud.go +++ b/cmd/cloud.go @@ -40,7 +40,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) var ( @@ -215,16 +215,16 @@ This will execute the test on the Load Impact cloud service. Use "k6 login cloud progress.Progress = testProgress.Progress fprintf(stdout, "%s\x1b[0K\r", progress.String()) } else { - log.WithError(progressErr).Error("Test progress error") + logrus.WithError(progressErr).Error("Test progress error") } if shouldExitLoop { break runningLoop } case sig := <-sigC: - log.WithField("sig", sig).Print("Exiting in response to signal...") + logrus.WithField("sig", sig).Print("Exiting in response to signal...") err := client.StopCloudTestRun(refID) if err != nil { - log.WithError(err).Error("Stop cloud test error") + logrus.WithError(err).Error("Stop cloud test error") } shouldExitLoop = true // Exit after the next GetTestProgress call } diff --git a/cmd/config.go b/cmd/config.go index 186e2ebff36..e44437be194 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -22,14 +22,18 @@ package cmd import ( "encoding/json" + "errors" "fmt" "os" "path/filepath" "strings" - "errors" - "github.com/kelseyhightower/envconfig" + "github.com/sirupsen/logrus" + "github.com/spf13/afero" + "github.com/spf13/pflag" + null "gopkg.in/guregu/null.v3" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/lib/scheduler" "github.com/loadimpact/k6/lib/types" @@ -38,10 +42,6 @@ import ( "github.com/loadimpact/k6/stats/influxdb" "github.com/loadimpact/k6/stats/kafka" "github.com/loadimpact/k6/stats/statsd/common" - log "github.com/sirupsen/logrus" - "github.com/spf13/afero" - "github.com/spf13/pflag" - null "gopkg.in/guregu/null.v3" ) // configFlagSet returns a FlagSet with the default run configuration flags. @@ -224,7 +224,7 @@ func deriveExecutionConfig(conf Config) (Config, error) { case conf.Iterations.Valid: if len(conf.Stages) > 0 { // stages isn't nil (not set) and isn't explicitly set to empty //TODO: make this an executionConflictConfigError in the next version - log.Warnf("Specifying both iterations and stages is deprecated and won't be supported in the future k6 versions") + logrus.Warn("Specifying both iterations and stages is deprecated and won't be supported in the future k6 versions") } result.Execution = getSharedIterationsExecution(conf.Iterations, conf.Duration, conf.VUs) @@ -233,12 +233,13 @@ func deriveExecutionConfig(conf Config) (Config, error) { case conf.Duration.Valid: if len(conf.Stages) > 0 { // stages isn't nil (not set) and isn't explicitly set to empty //TODO: make this an executionConflictConfigError in the next version - log.Warnf("Specifying both duration and stages is deprecated and won't be supported in the future k6 versions") + logrus.Warn("Specifying both duration and stages is deprecated and won't be supported in the future k6 versions") } if conf.Duration.Duration <= 0 { //TODO: make this an executionConflictConfigError in the next version - log.Warnf("Specifying infinite duration in this way is deprecated and won't be supported in the future k6 versions") + msg := "Specifying infinite duration in this way is deprecated and won't be supported in the future k6 versions" + logrus.Warn(msg) } else { result.Execution = getConstantLoopingVUsExecution(conf.Duration, conf.VUs) } @@ -249,7 +250,7 @@ func deriveExecutionConfig(conf Config) (Config, error) { default: if conf.Execution != nil { // If someone set this, regardless if its empty //TODO: remove this warning in the next version - log.Warnf("The execution settings are not functional in this k6 release, they will be ignored") + logrus.Warn("The execution settings are not functional in this k6 release, they will be ignored") } if len(conf.Execution) == 0 { // If unset or set to empty @@ -337,6 +338,6 @@ func validateConfig(conf Config) error { errMsg := errors.New(strings.Join(errMsgParts, "\n")) //TODO: actually return the error here instead of warning, so k6 aborts on config validation errors - log.Warn(errMsg) + logrus.Warn(errMsg) return nil } diff --git a/cmd/config_consolidation_test.go b/cmd/config_consolidation_test.go index c9cad95c422..74f206ba9e3 100644 --- a/cmd/config_consolidation_test.go +++ b/cmd/config_consolidation_test.go @@ -28,16 +28,17 @@ import ( "testing" "time" - "github.com/loadimpact/k6/lib" - "github.com/loadimpact/k6/lib/scheduler" - "github.com/loadimpact/k6/lib/testutils" - "github.com/loadimpact/k6/lib/types" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/afero" "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" null "gopkg.in/guregu/null.v3" + + "github.com/loadimpact/k6/lib" + "github.com/loadimpact/k6/lib/scheduler" + "github.com/loadimpact/k6/lib/testutils" + "github.com/loadimpact/k6/lib/types" ) // A helper funcion for setting arbitrary environment variables and @@ -416,7 +417,7 @@ func runTestCase( logHook *testutils.SimpleLogrusHook, ) { t.Logf("Test with opts=%#v and exp=%#v\n", testCase.options, testCase.expected) - log.SetOutput(testOutput{t}) + logrus.SetOutput(testOutput{t}) logHook.Drain() restoreEnv := setEnv(t, testCase.options.env) @@ -493,10 +494,10 @@ func runTestCase( func TestConfigConsolidation(t *testing.T) { // This test and its subtests shouldn't be ran in parallel, since they unfortunately have // to mess with shared global objects (env vars, variables, the log, ... santa?) - logHook := testutils.SimpleLogrusHook{HookedLevels: []log.Level{log.WarnLevel}} - log.AddHook(&logHook) - log.SetOutput(ioutil.Discard) - defer log.SetOutput(os.Stderr) + logHook := testutils.SimpleLogrusHook{HookedLevels: []logrus.Level{logrus.WarnLevel}} + logrus.AddHook(&logHook) + logrus.SetOutput(ioutil.Discard) + defer logrus.SetOutput(os.Stderr) for tcNum, testCase := range getConfigConsolidationTestCases() { flagSetInits := testCase.options.cliFlagSetInits diff --git a/cmd/root.go b/cmd/root.go index 67f2633fca8..2465c8ca8b2 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -23,19 +23,20 @@ package cmd import ( "fmt" "io" - golog "log" + "log" "os" "path/filepath" "sync" "github.com/fatih/color" - "github.com/loadimpact/k6/lib/consts" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" "github.com/shibukawa/configdir" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" + + "github.com/loadimpact/k6/lib/consts" ) var BannerColor = color.New(color.FgCyan) @@ -78,7 +79,7 @@ var RootCmd = &cobra.Command{ stdout.Writer = colorable.NewNonColorable(os.Stdout) stderr.Writer = colorable.NewNonColorable(os.Stderr) } - golog.SetOutput(log.StandardLogger().Writer()) + log.SetOutput(logrus.StandardLogger().Writer()) }, } @@ -86,7 +87,7 @@ var RootCmd = &cobra.Command{ // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := RootCmd.Execute(); err != nil { - log.Error(err.Error()) + logrus.Error(err.Error()) if e, ok := err.(ExitCode); ok { os.Exit(e.Code) } @@ -137,26 +138,26 @@ func fprintf(w io.Writer, format string, a ...interface{}) (n int) { type RawFormater struct{} // Format renders a single log entry -func (f RawFormater) Format(entry *log.Entry) ([]byte, error) { +func (f RawFormater) Format(entry *logrus.Entry) ([]byte, error) { return append([]byte(entry.Message), '\n'), nil } func setupLoggers(logFmt string) { if verbose { - log.SetLevel(log.DebugLevel) + logrus.SetLevel(logrus.DebugLevel) } - log.SetOutput(stderr) + logrus.SetOutput(stderr) switch logFmt { case "raw": - log.SetFormatter(&RawFormater{}) - log.Debug("Logger format: RAW") + logrus.SetFormatter(&RawFormater{}) + logrus.Debug("Logger format: RAW") case "json": - log.SetFormatter(&log.JSONFormatter{}) - log.Debug("Logger format: JSON") + logrus.SetFormatter(&logrus.JSONFormatter{}) + logrus.Debug("Logger format: JSON") default: - log.SetFormatter(&log.TextFormatter{ForceColors: stderrTTY, DisableColors: noColor}) - log.Debug("Logger format: TEXT") + logrus.SetFormatter(&logrus.TextFormatter{ForceColors: stderrTTY, DisableColors: noColor}) + logrus.Debug("Logger format: TEXT") } } diff --git a/cmd/run.go b/cmd/run.go index caf9df0e3dc..7e48a17299f 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -34,6 +34,13 @@ import ( "syscall" "time" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/spf13/afero" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + null "gopkg.in/guregu/null.v3" + "github.com/loadimpact/k6/api" "github.com/loadimpact/k6/core" "github.com/loadimpact/k6/core/local" @@ -43,12 +50,6 @@ import ( "github.com/loadimpact/k6/lib/types" "github.com/loadimpact/k6/loader" "github.com/loadimpact/k6/ui" - "github.com/pkg/errors" - log "github.com/sirupsen/logrus" - "github.com/spf13/afero" - "github.com/spf13/cobra" - "github.com/spf13/pflag" - null "gopkg.in/guregu/null.v3" ) const ( @@ -156,7 +157,7 @@ a commandline interface for interacting with it.`, } if conf.Iterations.Valid && conf.Iterations.Int64 < conf.VUsMax.Int64 { - log.Warnf( + logrus.Warnf( "All iterations (%d in this test run) are shared between all VUs, so some of the %d VUs will not execute even a single iteration!", conf.Iterations.Int64, conf.VUsMax.Int64, ) @@ -228,7 +229,7 @@ a commandline interface for interacting with it.`, fprintf(stdout, "%s server\r", initBar.String()) go func() { if err := api.ListenAndServe(address, engine); err != nil { - log.WithError(err).Warn("Error from API server") + logrus.WithError(err).Warn("Error from API server") } }() @@ -365,7 +366,7 @@ a commandline interface for interacting with it.`, select { case <-ticker.C: if quiet || !stdoutTTY { - l := log.WithFields(log.Fields{ + l := logrus.WithFields(logrus.Fields{ "t": engine.Executor.GetTime(), "i": engine.Executor.GetIterations(), }) @@ -399,7 +400,7 @@ a commandline interface for interacting with it.`, case err := <-errC: cancel() if err == nil { - log.Debug("Engine terminated cleanly") + logrus.Debug("Engine terminated cleanly") break mainLoop } @@ -407,26 +408,26 @@ a commandline interface for interacting with it.`, case lib.TimeoutError: switch string(e) { case "setup": - log.WithError(err).Error("Setup timeout") + logrus.WithError(err).Error("Setup timeout") return ExitCode{errors.New("Setup timeout"), setupTimeoutErrorCode} case "teardown": - log.WithError(err).Error("Teardown timeout") + logrus.WithError(err).Error("Teardown timeout") return ExitCode{errors.New("Teardown timeout"), teardownTimeoutErrorCode} default: - log.WithError(err).Error("Engine timeout") + logrus.WithError(err).Error("Engine timeout") return ExitCode{errors.New("Engine timeout"), genericTimeoutErrorCode} } default: - log.WithError(err).Error("Engine error") + logrus.WithError(err).Error("Engine error") return ExitCode{errors.New("Engine Error"), genericEngineErrorCode} } case sig := <-sigC: - log.WithField("sig", sig).Debug("Exiting in response to signal") + logrus.WithField("sig", sig).Debug("Exiting in response to signal") cancel() } } if quiet || !stdoutTTY { - e := log.WithFields(log.Fields{ + e := logrus.WithFields(logrus.Fields{ "t": engine.Executor.GetTime(), "i": engine.Executor.GetIterations(), }) @@ -442,7 +443,7 @@ a commandline interface for interacting with it.`, // Warn if no iterations could be completed. if engine.Executor.GetIterations() == 0 { - log.Warn("No data generated, because no script iterations finished, consider making the test duration longer") + logrus.Warn("No data generated, because no script iterations finished, consider making the test duration longer") } // Print the end-of-test summary. @@ -458,7 +459,7 @@ a commandline interface for interacting with it.`, } if conf.Linger.Bool { - log.Info("Linger set; waiting for Ctrl+C...") + logrus.Info("Linger set; waiting for Ctrl+C...") <-sigC } diff --git a/core/engine.go b/core/engine.go index 3e948836c88..96344b662aa 100644 --- a/core/engine.go +++ b/core/engine.go @@ -26,12 +26,13 @@ import ( "sync" "time" + "github.com/sirupsen/logrus" + "gopkg.in/guregu/null.v3" + "github.com/loadimpact/k6/core/local" "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/lib/metrics" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" - "gopkg.in/guregu/null.v3" ) const ( @@ -55,7 +56,7 @@ type Engine struct { NoThresholds bool NoSummary bool - logger *log.Logger + logger *logrus.Logger Metrics map[string]*stats.Metric MetricsLock sync.Mutex @@ -81,7 +82,7 @@ func NewEngine(ex lib.Executor, o lib.Options) (*Engine, error) { Metrics: make(map[string]*stats.Metric), Samples: make(chan stats.SampleContainer, o.MetricSamplesBufferSize.Int64), } - e.SetLogger(log.StandardLogger()) + e.SetLogger(logrus.StandardLogger()) if err := ex.SetVUsMax(o.VUsMax.Int64); err != nil { return nil, err @@ -124,7 +125,7 @@ func (e *Engine) Run(ctx context.Context) error { e.logger.Debug("Engine: Starting with parameters...") for i, st := range e.Executor.GetStages() { - fields := make(log.Fields) + fields := make(logrus.Fields) if st.Target.Valid { fields["tgt"] = st.Target.Int64 } @@ -134,7 +135,7 @@ func (e *Engine) Run(ctx context.Context) error { e.logger.WithFields(fields).Debugf(" - stage #%d", i) } - fields := make(log.Fields) + fields := make(logrus.Fields) if endTime := e.Executor.GetEndTime(); endTime.Valid { fields["time"] = endTime.Duration } @@ -252,12 +253,14 @@ func (e *Engine) IsTainted() bool { return e.thresholdsTainted } -func (e *Engine) SetLogger(l *log.Logger) { +// SetLogger sets Engine's loggger. +func (e *Engine) SetLogger(l *logrus.Logger) { e.logger = l e.Executor.SetLogger(l) } -func (e *Engine) GetLogger() *log.Logger { +// GetLogger returns Engine's current logger. +func (e *Engine) GetLogger() *logrus.Logger { return e.logger } diff --git a/core/engine_test.go b/core/engine_test.go index 784915594ad..eb2199e63d2 100644 --- a/core/engine_test.go +++ b/core/engine_test.go @@ -27,6 +27,12 @@ import ( "testing" "time" + "github.com/sirupsen/logrus" + logtest "github.com/sirupsen/logrus/hooks/test" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + null "gopkg.in/guregu/null.v3" + "github.com/loadimpact/k6/core/local" "github.com/loadimpact/k6/js" "github.com/loadimpact/k6/lib" @@ -36,11 +42,6 @@ import ( "github.com/loadimpact/k6/loader" "github.com/loadimpact/k6/stats" "github.com/loadimpact/k6/stats/dummy" - log "github.com/sirupsen/logrus" - logtest "github.com/sirupsen/logrus/hooks/test" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - null "gopkg.in/guregu/null.v3" ) type testErrorWithString string @@ -221,7 +222,7 @@ func TestNewEngineOptions(t *testing.T) { } func TestEngineRun(t *testing.T) { - log.SetLevel(log.DebugLevel) + logrus.SetLevel(logrus.DebugLevel) t.Run("exits with context", func(t *testing.T) { duration := 100 * time.Millisecond e, err := newTestEngine(nil, lib.Options{}) diff --git a/core/local/local.go b/core/local/local.go index d6bef798c4d..85b20c2a713 100644 --- a/core/local/local.go +++ b/core/local/local.go @@ -27,13 +27,14 @@ import ( "sync/atomic" "time" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + null "gopkg.in/guregu/null.v3" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/lib/metrics" "github.com/loadimpact/k6/lib/types" "github.com/loadimpact/k6/stats" - "github.com/pkg/errors" - log "github.com/sirupsen/logrus" - null "gopkg.in/guregu/null.v3" ) // TODO: totally rewrite this! @@ -51,7 +52,7 @@ type vuHandle struct { cancel context.CancelFunc } -func (h *vuHandle) run(logger *log.Logger, flow <-chan int64, iterDone chan<- struct{}) { +func (h *vuHandle) run(logger *logrus.Logger, flow <-chan int64, iterDone chan<- struct{}) { h.RLock() ctx := h.ctx h.RUnlock() @@ -89,7 +90,7 @@ func (h *vuHandle) run(logger *log.Logger, flow <-chan int64, iterDone chan<- st type Executor struct { Runner lib.Runner - Logger *log.Logger + Logger *logrus.Logger runLock sync.Mutex wg sync.WaitGroup @@ -139,7 +140,7 @@ func New(r lib.Runner) *Executor { return &Executor{ Runner: r, - Logger: log.StandardLogger(), + Logger: logrus.StandardLogger(), runSetup: true, runTeardown: true, endIters: -1, @@ -273,7 +274,7 @@ func (e *Executor) Run(parent context.Context, engineOut chan<- stats.SampleCont end := time.Duration(atomic.LoadInt64(&e.endTime)) at := time.Duration(atomic.AddInt64(&e.time, int64(d))) if end >= 0 && at >= end { - e.Logger.WithFields(log.Fields{"at": at, "end": end}).Debug("Local: Hit time limit") + e.Logger.WithFields(logrus.Fields{"at": at, "end": end}).Debug("Local: Hit time limit") cutoff = time.Now() return nil } @@ -311,7 +312,7 @@ func (e *Executor) Run(parent context.Context, engineOut chan<- stats.SampleCont end := atomic.LoadInt64(&e.endIters) at := atomic.AddInt64(&e.iters, 1) if end >= 0 && at >= end { - e.Logger.WithFields(log.Fields{"at": at, "end": end}).Debug("Local: Hit iteration limit") + e.Logger.WithFields(logrus.Fields{"at": at, "end": end}).Debug("Local: Hit iteration limit") return nil } case <-ctx.Done(): @@ -383,11 +384,13 @@ func (e *Executor) GetRunner() lib.Runner { return e.Runner } -func (e *Executor) SetLogger(l *log.Logger) { +// SetLogger sets Executor's logger. +func (e *Executor) SetLogger(l *logrus.Logger) { e.Logger = l } -func (e *Executor) GetLogger() *log.Logger { +// GetLogger returns current Executor's logger. +func (e *Executor) GetLogger() *logrus.Logger { return e.Logger } diff --git a/js/compiler/compiler.go b/js/compiler/compiler.go index 5adc2c2df8d..ff8e74de617 100644 --- a/js/compiler/compiler.go +++ b/js/compiler/compiler.go @@ -26,11 +26,11 @@ import ( "sync" "time" - "github.com/GeertJohan/go.rice" + rice "github.com/GeertJohan/go.rice" "github.com/dop251/goja" "github.com/dop251/goja/parser" "github.com/mitchellh/mapstructure" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) var ( @@ -105,7 +105,7 @@ func (c *Compiler) Transform(src, filename string) (code string, srcmap SourceMa if err != nil { return code, srcmap, err } - log.WithField("t", time.Since(startTime)).Debug("Babel: Transformed") + logrus.WithField("t", time.Since(startTime)).Debug("Babel: Transformed") vO := v.ToObject(c.vm) if err := c.vm.ExportTo(vO.Get("code"), &code); err != nil { diff --git a/js/console.go b/js/console.go index 88b2fd8076b..3a34ac4d650 100644 --- a/js/console.go +++ b/js/console.go @@ -26,17 +26,17 @@ import ( "strconv" "github.com/dop251/goja" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) // console represents a JS console implemented as a logrus.Logger. type console struct { - Logger *log.Logger + Logger *logrus.Logger } // Creates a console with the standard logrus logger. func newConsole() *console { - return &console{log.StandardLogger()} + return &console{logrus.StandardLogger()} } // Creates a console logger with its output set to the file at the provided `filepath`. @@ -46,16 +46,16 @@ func newFileConsole(filepath string) (*console, error) { return nil, err } - l := log.New() + l := logrus.New() l.SetOutput(f) //TODO: refactor to not rely on global variables, albeit external ones - l.SetFormatter(log.StandardLogger().Formatter) + l.SetFormatter(logrus.StandardLogger().Formatter) return &console{l}, nil } -func (c console) log(ctx *context.Context, level log.Level, msgobj goja.Value, args ...goja.Value) { +func (c console) log(ctx *context.Context, level logrus.Level, msgobj goja.Value, args ...goja.Value) { if ctx != nil && *ctx != nil { select { case <-(*ctx).Done(): @@ -64,20 +64,20 @@ func (c console) log(ctx *context.Context, level log.Level, msgobj goja.Value, a } } - fields := make(log.Fields) + fields := make(logrus.Fields) for i, arg := range args { fields[strconv.Itoa(i)] = arg.String() } msg := msgobj.ToString() e := c.Logger.WithFields(fields) switch level { - case log.DebugLevel: + case logrus.DebugLevel: e.Debug(msg) - case log.InfoLevel: + case logrus.InfoLevel: e.Info(msg) - case log.WarnLevel: + case logrus.WarnLevel: e.Warn(msg) - case log.ErrorLevel: + case logrus.ErrorLevel: e.Error(msg) } } @@ -87,17 +87,17 @@ func (c console) Log(ctx *context.Context, msg goja.Value, args ...goja.Value) { } func (c console) Debug(ctx *context.Context, msg goja.Value, args ...goja.Value) { - c.log(ctx, log.DebugLevel, msg, args...) + c.log(ctx, logrus.DebugLevel, msg, args...) } func (c console) Info(ctx *context.Context, msg goja.Value, args ...goja.Value) { - c.log(ctx, log.InfoLevel, msg, args...) + c.log(ctx, logrus.InfoLevel, msg, args...) } func (c console) Warn(ctx *context.Context, msg goja.Value, args ...goja.Value) { - c.log(ctx, log.WarnLevel, msg, args...) + c.log(ctx, logrus.WarnLevel, msg, args...) } func (c console) Error(ctx *context.Context, msg goja.Value, args ...goja.Value) { - c.log(ctx, log.ErrorLevel, msg, args...) + c.log(ctx, logrus.ErrorLevel, msg, args...) } diff --git a/js/console_test.go b/js/console_test.go index 8b0448d5fd1..aa0e137a51d 100644 --- a/js/console_test.go +++ b/js/console_test.go @@ -28,17 +28,17 @@ import ( "os" "testing" + "github.com/dop251/goja" + "github.com/sirupsen/logrus" + logtest "github.com/sirupsen/logrus/hooks/test" + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" null "gopkg.in/guregu/null.v3" - "github.com/dop251/goja" "github.com/loadimpact/k6/js/common" "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/loader" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" - logtest "github.com/sirupsen/logrus/hooks/test" - "github.com/spf13/afero" - "github.com/stretchr/testify/assert" ) func TestConsoleContext(t *testing.T) { @@ -94,20 +94,20 @@ func getSimpleRunnerWithFileFs(path, data string, fileFs afero.Fs) (*Runner, err lib.RuntimeOptions{}) } func TestConsole(t *testing.T) { - levels := map[string]log.Level{ - "log": log.InfoLevel, - "debug": log.DebugLevel, - "info": log.InfoLevel, - "warn": log.WarnLevel, - "error": log.ErrorLevel, + levels := map[string]logrus.Level{ + "log": logrus.InfoLevel, + "debug": logrus.DebugLevel, + "info": logrus.InfoLevel, + "warn": logrus.WarnLevel, + "error": logrus.ErrorLevel, } argsets := map[string]struct { Message string - Data log.Fields + Data logrus.Fields }{ `"string"`: {Message: "string"}, - `"string","a","b"`: {Message: "string", Data: log.Fields{"0": "a", "1": "b"}}, - `"string",1,2`: {Message: "string", Data: log.Fields{"0": "1", "1": "2"}}, + `"string","a","b"`: {Message: "string", Data: logrus.Fields{"0": "a", "1": "b"}}, + `"string",1,2`: {Message: "string", Data: logrus.Fields{"0": "1", "1": "2"}}, `{}`: {Message: "[object Object]"}, } for name, level := range levels { @@ -127,7 +127,7 @@ func TestConsole(t *testing.T) { assert.NoError(t, err) logger, hook := logtest.NewNullLogger() - logger.Level = log.DebugLevel + logger.Level = logrus.DebugLevel vu.Console.Logger = logger err = vu.RunOnce(context.Background()) @@ -140,7 +140,7 @@ func TestConsole(t *testing.T) { data := result.Data if data == nil { - data = make(log.Fields) + data = make(logrus.Fields) } assert.Equal(t, data, entry.Data) } @@ -152,20 +152,20 @@ func TestConsole(t *testing.T) { func TestFileConsole(t *testing.T) { var ( - levels = map[string]log.Level{ - "log": log.InfoLevel, - "debug": log.DebugLevel, - "info": log.InfoLevel, - "warn": log.WarnLevel, - "error": log.ErrorLevel, + levels = map[string]logrus.Level{ + "log": logrus.InfoLevel, + "debug": logrus.DebugLevel, + "info": logrus.InfoLevel, + "warn": logrus.WarnLevel, + "error": logrus.ErrorLevel, } argsets = map[string]struct { Message string - Data log.Fields + Data logrus.Fields }{ `"string"`: {Message: "string"}, - `"string","a","b"`: {Message: "string", Data: log.Fields{"0": "a", "1": "b"}}, - `"string",1,2`: {Message: "string", Data: log.Fields{"0": "1", "1": "2"}}, + `"string","a","b"`: {Message: "string", Data: logrus.Fields{"0": "a", "1": "b"}}, + `"string",1,2`: {Message: "string", Data: logrus.Fields{"0": "1", "1": "2"}}, `{}`: {Message: "[object Object]"}, } preExisting = map[string]bool{ @@ -218,7 +218,7 @@ func TestFileConsole(t *testing.T) { vu, err := r.newVU(samples) assert.NoError(t, err) - vu.Console.Logger.Level = log.DebugLevel + vu.Console.Logger.Level = logrus.DebugLevel hook := logtest.NewLocal(vu.Console.Logger) err = vu.RunOnce(context.Background()) @@ -235,7 +235,7 @@ func TestFileConsole(t *testing.T) { data := result.Data if data == nil { - data = make(log.Fields) + data = make(logrus.Fields) } assert.Equal(t, data, entry.Data) diff --git a/js/initcontext_test.go b/js/initcontext_test.go index de5a7012dc5..ef0ef8e719b 100644 --- a/js/initcontext_test.go +++ b/js/initcontext_test.go @@ -32,15 +32,16 @@ import ( "time" "github.com/dop251/goja" - "github.com/loadimpact/k6/js/common" - "github.com/loadimpact/k6/lib" - "github.com/loadimpact/k6/lib/netext" - "github.com/loadimpact/k6/stats" "github.com/oxtoacart/bpool" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/loadimpact/k6/js/common" + "github.com/loadimpact/k6/lib" + "github.com/loadimpact/k6/lib/netext" + "github.com/loadimpact/k6/stats" ) func TestInitContextRequire(t *testing.T) { @@ -369,8 +370,8 @@ func TestRequestWithBinaryFile(t *testing.T) { root, err := lib.NewGroup("", nil) assert.NoError(t, err) - logger := log.New() - logger.Level = log.DebugLevel + logger := logrus.New() + logger.Level = logrus.DebugLevel logger.Out = ioutil.Discard state := &lib.State{ diff --git a/js/modules/k6/html/gen/gen_elements.go b/js/modules/k6/html/gen/gen_elements.go index f3b14cd21f3..5b9098c2aa2 100644 --- a/js/modules/k6/html/gen/gen_elements.go +++ b/js/modules/k6/html/gen/gen_elements.go @@ -10,7 +10,7 @@ import ( "strings" "text/template" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) // Generate elements_gen.go. There are two sections of code which need to be generated. The selToElement function and the attribute accessor methods. @@ -293,7 +293,7 @@ func main() { fs := token.NewFileSet() parsedFile, parseErr := parser.ParseFile(fs, "elements.go", nil, 0) if parseErr != nil { - log.WithError(parseErr).Fatal("Could not parse elements.go") + logrus.WithError(parseErr).Fatal("Could not parse elements.go") } // Initialise the AstInspectState @@ -326,26 +326,26 @@ func main() { struct{ String, Url, Enum, Bool, GojaEnum, Int, Const TemplateType }{stringTemplate, urlTemplate, enumTemplate, boolTemplate, nullableEnumTemplate, intTemplate, constTemplate}, }) if err != nil { - log.WithError(err).Fatal("Unable to execute template") + logrus.WithError(err).Fatal("Unable to execute template") } src, err := format.Source(buf.Bytes()) if err != nil { - log.WithError(err).Fatal("format.Source on generated code failed") + logrus.WithError(err).Fatal("format.Source on generated code failed") } f, err := os.Create("elements_gen.go") if err != nil { - log.WithError(err).Fatal("Unable to create the file 'elements_gen.go'") + logrus.WithError(err).Fatal("Unable to create the file 'elements_gen.go'") } if _, err = f.Write(src); err != nil { - log.WithError(err).Fatal("Unable to write to 'elements_gen.go'") + logrus.WithError(err).Fatal("Unable to write to 'elements_gen.go'") } err = f.Close() if err != nil { - log.WithError(err).Fatal("Unable to close 'elements_gen.go'") + logrus.WithError(err).Fatal("Unable to close 'elements_gen.go'") } } diff --git a/js/runner.go b/js/runner.go index 4d3f97635bc..8858fd92d5c 100644 --- a/js/runner.go +++ b/js/runner.go @@ -31,18 +31,19 @@ import ( "time" "github.com/dop251/goja" - "github.com/loadimpact/k6/js/common" - "github.com/loadimpact/k6/lib" - "github.com/loadimpact/k6/lib/netext" - "github.com/loadimpact/k6/loader" - "github.com/loadimpact/k6/stats" "github.com/oxtoacart/bpool" "github.com/pkg/errors" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/afero" "github.com/viki-org/dnscache" "golang.org/x/net/http2" "golang.org/x/time/rate" + + "github.com/loadimpact/k6/js/common" + "github.com/loadimpact/k6/lib" + "github.com/loadimpact/k6/lib/netext" + "github.com/loadimpact/k6/loader" + "github.com/loadimpact/k6/stats" ) var errInterrupt = errors.New("context cancelled") @@ -52,7 +53,7 @@ var _ lib.Runner = &Runner{} type Runner struct { Bundle *Bundle - Logger *log.Logger + Logger *logrus.Logger defaultGroup *lib.Group BaseDialer net.Dialer @@ -88,7 +89,7 @@ func NewFromBundle(b *Bundle) (*Runner, error) { r := &Runner{ Bundle: b, - Logger: log.StandardLogger(), + Logger: logrus.StandardLogger(), defaultGroup: defaultGroup, BaseDialer: net.Dialer{ Timeout: 30 * time.Second, diff --git a/lib/executor.go b/lib/executor.go index 9c955189d00..668c0e18da3 100644 --- a/lib/executor.go +++ b/lib/executor.go @@ -24,10 +24,11 @@ import ( "context" "time" + "github.com/sirupsen/logrus" + null "gopkg.in/guregu/null.v3" + "github.com/loadimpact/k6/lib/types" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" - null "gopkg.in/guregu/null.v3" ) // An Executor is in charge of scheduling VUs created by a wrapped Runner, but decouples how you @@ -46,8 +47,8 @@ type Executor interface { GetRunner() Runner // Get and set the logger. This is propagated to the Runner. - GetLogger() *log.Logger - SetLogger(l *log.Logger) + GetLogger() *logrus.Logger + SetLogger(l *logrus.Logger) // Get and set the list of stages. GetStages() []Stage diff --git a/lib/netext/httpext/httpdebug_transport.go b/lib/netext/httpext/httpdebug_transport.go index 7441aeaf8fa..1d4124ece13 100644 --- a/lib/netext/httpext/httpdebug_transport.go +++ b/lib/netext/httpext/httpdebug_transport.go @@ -25,7 +25,7 @@ import ( "net/http" "net/http/httputil" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) type httpDebugTransport struct { @@ -50,7 +50,7 @@ func (t httpDebugTransport) RoundTrip(req *http.Request) (*http.Response, error) func (t httpDebugTransport) debugRequest(req *http.Request) { dump, err := httputil.DumpRequestOut(req, t.httpDebugOption == "full") if err != nil { - log.Fatal(err) //TODO: fix... + logrus.Fatal(err) //TODO: fix... } fmt.Printf("Request:\n%s\n", dump) //TODO: fix... } @@ -59,7 +59,7 @@ func (t httpDebugTransport) debugResponse(res *http.Response) { if res != nil { dump, err := httputil.DumpResponse(res, t.httpDebugOption == "full") if err != nil { - log.Fatal(err) //TODO: fix... + logrus.Fatal(err) //TODO: fix... } fmt.Printf("Response:\n%s\n", dump) //TODO: fix... } diff --git a/lib/netext/httpext/request.go b/lib/netext/httpext/request.go index 3c454358e0d..e0e5e7f8d24 100644 --- a/lib/netext/httpext/request.go +++ b/lib/netext/httpext/request.go @@ -39,10 +39,11 @@ import ( ntlmssp "github.com/Azure/go-ntlmssp" "github.com/andybalholm/brotli" "github.com/klauspost/compress/zstd" + "github.com/sirupsen/logrus" + null "gopkg.in/guregu/null.v3" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" - null "gopkg.in/guregu/null.v3" ) // HTTPRequestCookie is a representation of a cookie used for request objects @@ -461,7 +462,7 @@ func MakeRequest(ctx context.Context, preq *ParsedHTTPRequest) (*Response, error if l > 0 { url = via[0].URL } - state.Logger.WithFields(log.Fields{"url": url.String()}).Warnf( + state.Logger.WithFields(logrus.Fields{"url": url.String()}).Warnf( "Stopped after %d redirects and returned the redirection; pass { redirects: n }"+ " in request params or set global maxRedirects to silence this", l) } diff --git a/lib/state.go b/lib/state.go index 36a2614e769..08df1ee05f9 100644 --- a/lib/state.go +++ b/lib/state.go @@ -27,10 +27,11 @@ import ( "net/http" "net/http/cookiejar" - "github.com/loadimpact/k6/stats" "github.com/oxtoacart/bpool" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "golang.org/x/time/rate" + + "github.com/loadimpact/k6/stats" ) // DialContexter is an interface that can dial with a context @@ -44,7 +45,7 @@ type State struct { Options Options // Logger. Avoid using the global logger. - Logger *log.Logger + Logger *logrus.Logger // Current group; all emitted metrics are tagged with this. Group *Group diff --git a/lib/testutils/logrus_hook.go b/lib/testutils/logrus_hook.go index 4a355bf8ba0..751473184d2 100644 --- a/lib/testutils/logrus_hook.go +++ b/lib/testutils/logrus_hook.go @@ -3,24 +3,24 @@ package testutils import ( "sync" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) // SimpleLogrusHook implements the logrus.Hook interface and could be used to check // if log messages were outputted type SimpleLogrusHook struct { - HookedLevels []log.Level + HookedLevels []logrus.Level mutex sync.Mutex - messageCache []log.Entry + messageCache []logrus.Entry } // Levels just returns whatever was stored in the HookedLevels slice -func (smh *SimpleLogrusHook) Levels() []log.Level { +func (smh *SimpleLogrusHook) Levels() []logrus.Level { return smh.HookedLevels } // Fire saves whatever message the logrus library passed in the cache -func (smh *SimpleLogrusHook) Fire(e *log.Entry) error { +func (smh *SimpleLogrusHook) Fire(e *logrus.Entry) error { smh.mutex.Lock() defer smh.mutex.Unlock() smh.messageCache = append(smh.messageCache, *e) @@ -28,12 +28,12 @@ func (smh *SimpleLogrusHook) Fire(e *log.Entry) error { } // Drain returns the currently stored messages and deletes them from the cache -func (smh *SimpleLogrusHook) Drain() []log.Entry { +func (smh *SimpleLogrusHook) Drain() []logrus.Entry { smh.mutex.Lock() defer smh.mutex.Unlock() res := smh.messageCache - smh.messageCache = []log.Entry{} + smh.messageCache = []logrus.Entry{} return res } -var _ log.Hook = &SimpleLogrusHook{} +var _ logrus.Hook = &SimpleLogrusHook{} diff --git a/loader/loader.go b/loader/loader.go index eb94568a24f..0983ed4016a 100644 --- a/loader/loader.go +++ b/loader/loader.go @@ -32,7 +32,7 @@ import ( "time" "github.com/pkg/errors" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/afero" ) @@ -145,8 +145,8 @@ func Dir(old *url.URL) *url.URL { func Load( filesystems map[string]afero.Fs, moduleSpecifier *url.URL, originalModuleSpecifier string, ) (*SourceData, error) { - log.WithFields( - log.Fields{ + logrus.WithFields( + logrus.Fields{ "moduleSpecifier": moduleSpecifier, "original moduleSpecifier": originalModuleSpecifier, }).Debug("Loading...") @@ -184,7 +184,7 @@ func Load( return nil, err } case moduleSpecifier.Scheme == "": - log.WithField("url", moduleSpecifier).Warning( + logrus.WithField("url", moduleSpecifier).Warning( "A url was resolved but it didn't have scheme. " + "This will be deprecated in the future and all remote modules will " + "need to explicitly use `https` as scheme") @@ -261,7 +261,7 @@ func pickLoader(path string) (string, loaderFunc, []string) { } func fetch(u string) ([]byte, error) { - log.WithField("url", u).Debug("Fetching source...") + logrus.WithField("url", u).Debug("Fetching source...") startTime := time.Now() res, err := http.Get(u) if err != nil { @@ -283,7 +283,7 @@ func fetch(u string) ([]byte, error) { return nil, err } - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "url": u, "t": time.Since(startTime), "len": len(data), diff --git a/stats/cloud/collector.go b/stats/cloud/collector.go index 8fa8ec07453..ec2c90e26ed 100644 --- a/stats/cloud/collector.go +++ b/stats/cloud/collector.go @@ -27,17 +27,16 @@ import ( "sync" "time" - "github.com/loadimpact/k6/lib/metrics" - "github.com/loadimpact/k6/lib/netext" - "github.com/loadimpact/k6/lib/netext/httpext" - "github.com/loadimpact/k6/loader" "github.com/pkg/errors" - + "github.com/sirupsen/logrus" "gopkg.in/guregu/null.v3" "github.com/loadimpact/k6/lib" + "github.com/loadimpact/k6/lib/metrics" + "github.com/loadimpact/k6/lib/netext" + "github.com/loadimpact/k6/lib/netext/httpext" + "github.com/loadimpact/k6/loader" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" ) // TestName is the default Load Impact Cloud test name @@ -132,7 +131,7 @@ func New(conf Config, src *loader.SourceData, opts lib.Options, version string) } if !conf.Token.Valid && conf.DeprecatedToken.Valid { - log.Warn("K6CLOUD_TOKEN is deprecated and will be removed. Use K6_CLOUD_TOKEN instead.") + logrus.Warn("K6CLOUD_TOKEN is deprecated and will be removed. Use K6_CLOUD_TOKEN instead.") conf.Token = conf.DeprecatedToken } @@ -173,13 +172,13 @@ func (c *Collector) Init() error { c.referenceID = response.ReferenceID if response.ConfigOverride != nil { - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "override": response.ConfigOverride, }).Debug("Cloud: overriding config options") c.config = c.config.Apply(*response.ConfigOverride) } - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "name": c.config.Name, "projectId": c.config.ProjectID, "duration": c.duration, @@ -402,7 +401,7 @@ func (c *Collector) aggregateHTTPTrails(waitPeriod time.Duration) { aggrData.CalcAverages() if aggrData.Count > 0 { - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "http_samples": aggrData.Count, }).Debug("Aggregated HTTP metrics") newSamples = append(newSamples, &Sample{ @@ -452,7 +451,7 @@ func (c *Collector) pushMetrics() { c.bufferSamples = nil c.bufferMutex.Unlock() - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "samples": len(buffer), }).Debug("Pushing metrics to cloud") @@ -463,7 +462,7 @@ func (c *Collector) pushMetrics() { } err := c.client.PushMetric(c.referenceID, c.config.NoCompress.Bool, buffer[:size]) if err != nil { - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "error": err, }).Warn("Failed to send metrics to cloud") } @@ -488,7 +487,7 @@ func (c *Collector) testFinished() { } } - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "ref": c.referenceID, "tainted": testTainted, }).Debug("Sending test finished") @@ -500,7 +499,7 @@ func (c *Collector) testFinished() { err := c.client.TestFinished(c.referenceID, thresholdResults, testTainted, runStatus) if err != nil { - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "error": err, }).Warn("Failed to send test finished to cloud") } diff --git a/stats/dummy/collector.go b/stats/dummy/collector.go index 47dc7ed5b3b..b6e9bf69d05 100644 --- a/stats/dummy/collector.go +++ b/stats/dummy/collector.go @@ -23,9 +23,10 @@ package dummy import ( "context" + "github.com/sirupsen/logrus" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" ) // Collector implements the lib.Collector interface and should be used only for testing @@ -48,7 +49,7 @@ func (c *Collector) MakeConfig() interface{} { return nil } // Run just blocks until the context is done func (c *Collector) Run(ctx context.Context) { <-ctx.Done() - log.Debugf("finished status: %d", c.RunStatus) + logrus.Debugf("finished status: %d", c.RunStatus) } // Collect just appends all of the samples passed to it to the internal sample slice. diff --git a/stats/influxdb/collector.go b/stats/influxdb/collector.go index 9041c030a7d..e473507dc06 100644 --- a/stats/influxdb/collector.go +++ b/stats/influxdb/collector.go @@ -26,9 +26,10 @@ import ( "time" "github.com/influxdata/influxdb/client/v2" + "github.com/sirupsen/logrus" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" ) const ( @@ -65,14 +66,14 @@ func (c *Collector) Init() error { // usually means we're either a non-admin user to an existing DB or connecting over UDP. _, err := c.Client.Query(client.NewQuery("CREATE DATABASE "+c.BatchConf.Database, "", "")) if err != nil { - log.WithError(err).Debug("InfluxDB: Couldn't create database; most likely harmless") + logrus.WithError(err).Debug("InfluxDB: Couldn't create database; most likely harmless") } return nil } func (c *Collector) Run(ctx context.Context) { - log.Debug("InfluxDB: Running!") + logrus.Debug("InfluxDB: Running!") ticker := time.NewTicker(pushInterval) for { select { @@ -103,20 +104,20 @@ func (c *Collector) commit() { c.buffer = nil c.bufferLock.Unlock() - log.Debug("InfluxDB: Committing...") + logrus.Debug("InfluxDB: Committing...") batch, err := c.batchFromSamples(samples) if err != nil { return } - log.WithField("points", len(batch.Points())).Debug("InfluxDB: Writing...") + logrus.WithField("points", len(batch.Points())).Debug("InfluxDB: Writing...") startTime := time.Now() if err := c.Client.Write(batch); err != nil { - log.WithError(err).Error("InfluxDB: Couldn't write stats") + logrus.WithError(err).Error("InfluxDB: Couldn't write stats") } t := time.Since(startTime) - log.WithField("t", t).Debug("InfluxDB: Batch written!") + logrus.WithField("t", t).Debug("InfluxDB: Batch written!") } func (c *Collector) extractTagsToValues(tags map[string]string, values map[string]interface{}) map[string]interface{} { @@ -132,7 +133,7 @@ func (c *Collector) extractTagsToValues(tags map[string]string, values map[strin func (c *Collector) batchFromSamples(samples []stats.Sample) (client.BatchPoints, error) { batch, err := client.NewBatchPoints(c.BatchConf) if err != nil { - log.WithError(err).Error("InfluxDB: Couldn't make a batch") + logrus.WithError(err).Error("InfluxDB: Couldn't make a batch") return nil, err } @@ -162,7 +163,7 @@ func (c *Collector) batchFromSamples(samples []stats.Sample) (client.BatchPoints sample.Time, ) if err != nil { - log.WithError(err).Error("InfluxDB: Couldn't make point from sample!") + logrus.WithError(err).Error("InfluxDB: Couldn't make point from sample!") return nil, err } batch.AddPoint(p) diff --git a/stats/json/collector.go b/stats/json/collector.go index 6801a568bdb..a3986c89a8f 100644 --- a/stats/json/collector.go +++ b/stats/json/collector.go @@ -26,10 +26,11 @@ import ( "io" "os" + "github.com/sirupsen/logrus" + "github.com/spf13/afero" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" - "github.com/spf13/afero" ) type Collector struct { @@ -82,7 +83,7 @@ func (c *Collector) Init() error { func (c *Collector) SetRunStatus(status lib.RunStatus) {} func (c *Collector) Run(ctx context.Context) { - log.WithField("filename", c.fname).Debug("JSON: Writing JSON metrics") + logrus.WithField("filename", c.fname).Debug("JSON: Writing JSON metrics") <-ctx.Done() _ = c.outfile.Close() } @@ -97,7 +98,7 @@ func (c *Collector) HandleMetric(m *stats.Metric) { row, err := json.Marshal(env) if env == nil || err != nil { - log.WithField("filename", c.fname).Warning( + logrus.WithField("filename", c.fname).Warning( "JSON: Envelope is nil or Metric couldn't be marshalled to JSON") return } @@ -105,7 +106,7 @@ func (c *Collector) HandleMetric(m *stats.Metric) { row = append(row, '\n') _, err = c.outfile.Write(row) if err != nil { - log.WithField("filename", c.fname).Error("JSON: Error writing to file") + logrus.WithField("filename", c.fname).Error("JSON: Error writing to file") } } @@ -119,14 +120,14 @@ func (c *Collector) Collect(scs []stats.SampleContainer) { if err != nil || env == nil { // Skip metric if it can't be made into JSON or envelope is null. - log.WithField("filename", c.fname).Warning( + logrus.WithField("filename", c.fname).Warning( "JSON: Envelope is nil or Sample couldn't be marshalled to JSON") continue } row = append(row, '\n') _, err = c.outfile.Write(row) if err != nil { - log.WithField("filename", c.fname).Error("JSON: Error writing to file") + logrus.WithField("filename", c.fname).Error("JSON: Error writing to file") continue } } diff --git a/stats/kafka/collector.go b/stats/kafka/collector.go index 1de508ead47..ac23cddcb02 100644 --- a/stats/kafka/collector.go +++ b/stats/kafka/collector.go @@ -27,11 +27,12 @@ import ( "time" "github.com/Shopify/sarama" + "github.com/sirupsen/logrus" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/stats" "github.com/loadimpact/k6/stats/influxdb" jsonc "github.com/loadimpact/k6/stats/json" - log "github.com/sirupsen/logrus" ) // Collector implements the lib.Collector interface and should be used only for testing @@ -61,7 +62,7 @@ func (c *Collector) Init() error { return nil } // Run just blocks until the context is done func (c *Collector) Run(ctx context.Context) { - log.Debug("Kafka: Running!") + logrus.Debug("Kafka: Running!") ticker := time.NewTicker(time.Duration(c.Config.PushInterval.Duration)) for { select { @@ -72,7 +73,7 @@ func (c *Collector) Run(ctx context.Context) { err := c.Producer.Close() if err != nil { - log.WithError(err).Error("Kafka: Failed to close producer.") + logrus.WithError(err).Error("Kafka: Failed to close producer.") } return } @@ -146,20 +147,20 @@ func (c *Collector) pushMetrics() { // Format the samples formattedSamples, err := c.formatSamples(samples) if err != nil { - log.WithError(err).Error("Kafka: Couldn't format the samples") + logrus.WithError(err).Error("Kafka: Couldn't format the samples") return } // Send the samples - log.Debug("Kafka: Delivering...") + logrus.Debug("Kafka: Delivering...") for _, sample := range formattedSamples { msg := &sarama.ProducerMessage{Topic: c.Config.Topic.String, Value: sarama.StringEncoder(sample)} partition, offset, err := c.Producer.SendMessage(msg) if err != nil { - log.WithError(err).Error("Kafka: failed to send message.") + logrus.WithError(err).Error("Kafka: failed to send message.") } else { - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "partition": partition, "offset": offset, }).Debug("Kafka: message sent.") @@ -167,5 +168,5 @@ func (c *Collector) pushMetrics() { } t := time.Since(startTime) - log.WithField("t", t).Debug("Kafka: Delivered!") + logrus.WithField("t", t).Debug("Kafka: Delivered!") } diff --git a/stats/statsd/common/collector.go b/stats/statsd/common/collector.go index 99d4b2ec638..fc281221239 100644 --- a/stats/statsd/common/collector.go +++ b/stats/statsd/common/collector.go @@ -27,9 +27,10 @@ import ( "time" "github.com/DataDog/datadog-go/statsd" + "github.com/sirupsen/logrus" + "github.com/loadimpact/k6/lib" "github.com/loadimpact/k6/stats" - log "github.com/sirupsen/logrus" ) var _ lib.Collector = &Collector{} @@ -42,7 +43,7 @@ type Collector struct { // of those tags that should be sent. No tags are send in case of ProcessTags being null ProcessTags func(map[string]string) []string - logger *log.Entry + logger *logrus.Entry client *statsd.Client startTime time.Time buffer []*Sample @@ -51,7 +52,7 @@ type Collector struct { // Init sets up the collector func (c *Collector) Init() (err error) { - c.logger = log.WithField("type", c.Type) + c.logger = logrus.WithField("type", c.Type) if address := c.Config.Addr.String; address == "" { err = fmt.Errorf( "connection string is invalid. Received: \"%+s\"",