Skip to content

Commit

Permalink
Use logrus import without alias
Browse files Browse the repository at this point in the history
Also add some comments to keep linter silent.

Closes #1016
  • Loading branch information
cuonglm authored and na-- committed Aug 13, 2019
1 parent f8a88b6 commit e3c279f
Show file tree
Hide file tree
Showing 28 changed files with 253 additions and 230 deletions.
14 changes: 8 additions & 6 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)

Expand All @@ -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")
}
})
}
13 changes: 7 additions & 6 deletions api/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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()
Expand All @@ -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"])
})
Expand Down
8 changes: 4 additions & 4 deletions cmd/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"

log "github.com/sirupsen/logrus"
"github.com/sirupsen/logrus"
)

var (
Expand Down Expand Up @@ -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
}
Expand Down
23 changes: 12 additions & 11 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
Expand All @@ -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
Expand Down Expand Up @@ -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
}
21 changes: 11 additions & 10 deletions cmd/config_consolidation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
29 changes: 15 additions & 14 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -78,15 +79,15 @@ 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())
},
}

// Execute adds all child commands to the root command sets flags appropriately.
// 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)
}
Expand Down Expand Up @@ -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")
}

}
Loading

0 comments on commit e3c279f

Please sign in to comment.