diff --git a/cmd/doctor.go b/cmd/doctor.go index b525974..a24bf35 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -19,7 +19,6 @@ package cmd import ( "fmt" "gatehill.io/imposter/engine" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "strings" ) @@ -42,7 +41,7 @@ var doctorCmd = &cobra.Command{ Long: `Checks prerequisites for running Imposter, including those needed by the engines.`, Run: func(cmd *cobra.Command, args []string) { - logrus.Debug("running check up...") + logger.Debug("running check up...") println(checkPrereqs()) }, } diff --git a/cmd/down.go b/cmd/down.go index 9e7923f..5929504 100644 --- a/cmd/down.go +++ b/cmd/down.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/engine" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" "path/filepath" @@ -44,14 +43,14 @@ func init() { } func stopAll(engineType engine.EngineType) { - logrus.Info("stopping all managed mocks...") + logger.Info("stopping all managed mocks...") configDir := filepath.Join(os.TempDir(), "imposter-down") mockEngine := engine.BuildEngine(engineType, configDir, engine.StartOptions{}) if stopped := mockEngine.StopAllManaged(); stopped > 0 { - logrus.Infof("stopped %d managed mock(s)", stopped) + logger.Infof("stopped %d managed mock(s)", stopped) } else { - logrus.Info("no managed mocks were found") + logger.Info("no managed mocks were found") } } diff --git a/cmd/engine_list.go b/cmd/engine_list.go index 8adcb80..84ca8cc 100644 --- a/cmd/engine_list.go +++ b/cmd/engine_list.go @@ -19,7 +19,6 @@ package cmd import ( "gatehill.io/imposter/engine" "github.com/olekukonko/tablewriter" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -50,14 +49,14 @@ If engine type is not specified, it defaults to all.`, } func list(engineTypes []engine.EngineType) { - logrus.Tracef("listing engines") + logger.Tracef("listing engines") var available []engine.EngineMetadata for _, e := range engineTypes { library := engine.GetLibrary(e) engines, err := library.List() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } available = append(available, engines...) } diff --git a/cmd/engine_pull.go b/cmd/engine_pull.go index f0a3f6f..9461d46 100644 --- a/cmd/engine_pull.go +++ b/cmd/engine_pull.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/engine" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -52,9 +51,9 @@ func pull(version string, engineType engine.EngineType, pullPolicy engine.PullPo downloader := engine.GetLibrary(engineType).GetProvider(version) err := downloader.Provide(pullPolicy) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } - logrus.Infof("pulled engine version %v", version) + logger.Infof("pulled engine version %v", version) } func init() { diff --git a/cmd/plugin_install.go b/cmd/plugin_install.go index 7774486..9aadd15 100644 --- a/cmd/plugin_install.go +++ b/cmd/plugin_install.go @@ -19,7 +19,6 @@ package cmd import ( "gatehill.io/imposter/engine" "gatehill.io/imposter/plugin" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -65,11 +64,11 @@ func installPlugins(plugins []string, version string, saveDefault bool) { ensured, err = plugin.EnsurePlugins(plugins, version, saveDefault) } if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } if ensured == 0 { - logrus.Infof("no plugins to install") + logger.Infof("no plugins to install") } else { - logrus.Infof("%d plugin(s) installed", ensured) + logger.Infof("%d plugin(s) installed", ensured) } } diff --git a/cmd/remote_config.go b/cmd/remote_config.go index a808b25..af0b9d3 100644 --- a/cmd/remote_config.go +++ b/cmd/remote_config.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/remote" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -74,31 +73,31 @@ func init() { func setRemoteConfigType(dir string, remoteType string) { active, err := remote.SaveActiveRemoteType(dir, remoteType) if err != nil { - logrus.Fatalf("failed to set remote type: %s", err) + logger.Fatalf("failed to set remote type: %s", err) } - logrus.Infof("set remote type to '%s' for remote: %s", remoteType, active.Name) + logger.Infof("set remote type to '%s' for remote: %s", remoteType, active.Name) } func setRemoteConfigUrl(dir string, url string) { active, r, err := remote.LoadActive(dir) if err != nil { - logrus.Fatalf("failed to load remote: %s", err) + logger.Fatalf("failed to load remote: %s", err) } err = (*r).SetUrl(url) if err != nil { - logrus.Fatalf("failed to set remote URL: %s", err) + logger.Fatalf("failed to set remote URL: %s", err) } - logrus.Infof("set remote URL to '%s' for remote: %s", url, active.Name) + logger.Infof("set remote URL to '%s' for remote: %s", url, active.Name) } func setRemoteConfigToken(dir string, token string) { active, r, err := remote.LoadActive(dir) if err != nil { - logrus.Fatalf("failed to load remote: %s", err) + logger.Fatalf("failed to load remote: %s", err) } err = (*r).SetToken(token) if err != nil { - logrus.Fatalf("failed to set remote token: %s", err) + logger.Fatalf("failed to set remote token: %s", err) } - logrus.Infof("set remote token for remote: %s", active.Name) + logger.Infof("set remote token for remote: %s", active.Name) } diff --git a/cmd/remote_deploy.go b/cmd/remote_deploy.go index 2f6a3db..801f121 100644 --- a/cmd/remote_deploy.go +++ b/cmd/remote_deploy.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/remote" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -46,13 +45,13 @@ func init() { func remoteDeploy(dir string) { active, r, err := remote.LoadActive(dir) if err != nil { - logrus.Fatalf("failed to load remote: %s", err) + logger.Fatalf("failed to load remote: %s", err) } - logrus.Infof("deploying workspace '%s' to remote: %s", active.Name, (*r).GetUrl()) + logger.Infof("deploying workspace '%s' to remote: %s", active.Name, (*r).GetUrl()) endpoint, err := (*r).Deploy() if err != nil { - logrus.Fatalf("failed to deploy workspace: %s", err) + logger.Fatalf("failed to deploy workspace: %s", err) } - logrus.Infof("deployed workspace '%s'\nBase URL: %s\nSpec: %s\nStatus: %s", active.Name, endpoint.BaseUrl, endpoint.SpecUrl, endpoint.StatusUrl) + logger.Infof("deployed workspace '%s'\nBase URL: %s\nSpec: %s\nStatus: %s", active.Name, endpoint.BaseUrl, endpoint.SpecUrl, endpoint.StatusUrl) } diff --git a/cmd/remote_show.go b/cmd/remote_show.go index 276c2a3..f055c8d 100644 --- a/cmd/remote_show.go +++ b/cmd/remote_show.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/remote" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -46,17 +45,17 @@ func init() { func showRemote(dir string) { active, r, err := remote.LoadActive(dir) if err != nil { - logrus.Fatalf("failed to load remote: %s", err) + logger.Fatalf("failed to load remote: %s", err) } remoteType := (*r).GetType() url := (*r).GetUrl() token, err := (*r).GetObfuscatedToken() if err != nil { - logrus.Fatalf("failed to get remote token: %s", err) + logger.Fatalf("failed to get remote token: %s", err) } - logrus.Infof(`Workspace '%s' remote: + logger.Infof(`Workspace '%s' remote: Type: %s URL: %s Token: %s`, active.Name, remoteType, url, token) diff --git a/cmd/remote_status.go b/cmd/remote_status.go index bf3a1b7..ff95c7c 100644 --- a/cmd/remote_status.go +++ b/cmd/remote_status.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/remote" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" "time" @@ -47,14 +46,14 @@ func init() { func showRemoteStatus(dir string) { active, r, err := remote.LoadActive(dir) if err != nil { - logrus.Fatalf("failed to load remote: %s", err) + logger.Fatalf("failed to load remote: %s", err) } status, err := (*r).GetStatus() if err != nil { - logrus.Fatalf("failed to get remote status: %s", err) + logger.Fatalf("failed to get remote status: %s", err) } lastModified := time.UnixMilli(int64(status.LastModified)) - logrus.Infof("Workspace '%s' remote status: %s\nLast modified: %v", active.Name, status.Status, lastModified) + logger.Infof("Workspace '%s' remote status: %s\nLast modified: %v", active.Name, status.Status, lastModified) } diff --git a/cmd/root.go b/cmd/root.go index e469756..fe55603 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -19,13 +19,15 @@ package cmd import ( "gatehill.io/imposter/config" "gatehill.io/imposter/engine" - "github.com/sirupsen/logrus" + "gatehill.io/imposter/logging" "github.com/spf13/cobra" "github.com/spf13/viper" "os" "strings" ) +var logger = logging.GetLogger() + var rootFlags = struct { cfgFile string flagPrintVersion bool @@ -101,12 +103,12 @@ func initConfig() { // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { - logrus.Tracef("using CLI config file: %v", viper.ConfigFileUsed()) + logger.Tracef("using CLI config file: %v", viper.ConfigFileUsed()) } } func initLogging() { if rootFlags.logLevel != "" { - config.SetLogLevel(rootFlags.logLevel) + logging.SetLogLevel(rootFlags.logLevel) } } diff --git a/cmd/up.go b/cmd/up.go index d43a282..a12ed70 100644 --- a/cmd/up.go +++ b/cmd/up.go @@ -23,7 +23,6 @@ import ( "gatehill.io/imposter/fileutil" "gatehill.io/imposter/impostermodel" "gatehill.io/imposter/plugin" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" "os" @@ -74,7 +73,7 @@ If CONFIG_DIR is not specified, the current working directory is used.`, if upFlags.flagEnsurePlugins { _, err := plugin.EnsureDefaultPlugins(version) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } } @@ -85,7 +84,7 @@ If CONFIG_DIR is not specified, the current working directory is used.`, configDir, _ = filepath.Abs(args[0]) } if err := validateConfigExists(configDir, upFlags.flagScaffoldMissing); err != nil { - logrus.Fatal(err) + logger.Fatal(err) } startOptions := engine.StartOptions{ @@ -145,7 +144,7 @@ func validateConfigExists(configDir string, scaffoldMissing bool) error { } if scaffoldMissing { - logrus.Infof("scaffolding Imposter configuration files") + logger.Infof("scaffolding Imposter configuration files") impostermodel.CreateFromSpecs(configDir, false, false, impostermodel.ScriptEngineNone) return nil } @@ -166,14 +165,14 @@ func start(lib *engine.EngineLibrary, startOptions engine.StartOptions, configDi go func() { for { <-dirUpdated - logrus.Infof("detected change in: %v - triggering restart", configDir) + logger.Infof("detected change in: %v - triggering restart", configDir) mockEngine.Restart(wg) } }() } wg.Wait() - logrus.Debug("shutting down") + logger.Debug("shutting down") } // listen for an interrupt from the OS, then attempt engine cleanup diff --git a/cmd/version.go b/cmd/version.go index 38aa9bf..0c4191d 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -20,7 +20,6 @@ import ( "fmt" "gatehill.io/imposter/config" "gatehill.io/imposter/engine" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -64,7 +63,7 @@ func getInstalledEngineVersion(engineType engine.EngineType, version string) str }) versionString, err := mockEngine.GetVersionString() if err != nil { - logrus.Warn(err) + logger.Warn(err) return "error" } return versionString diff --git a/cmd/workspace_delete.go b/cmd/workspace_delete.go index 3cc3655..705f8d7 100644 --- a/cmd/workspace_delete.go +++ b/cmd/workspace_delete.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/workspace" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -48,7 +47,7 @@ func init() { func deleteWorkspace(dir string, name string) { err := workspace.Delete(dir, name) if err != nil { - logrus.Fatalf("failed to delete workspace: %s", err) + logger.Fatalf("failed to delete workspace: %s", err) } - logrus.Infof("deleted workspace '%s'", name) + logger.Infof("deleted workspace '%s'", name) } diff --git a/cmd/workspace_list.go b/cmd/workspace_list.go index 0f7f4d4..6020318 100644 --- a/cmd/workspace_list.go +++ b/cmd/workspace_list.go @@ -19,7 +19,6 @@ package cmd import ( "gatehill.io/imposter/workspace" "github.com/olekukonko/tablewriter" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -47,11 +46,11 @@ func init() { func listWorkspaces(dir string) { workspaces, err := workspace.List(dir) if err != nil { - logrus.Fatalf("failed to list workspaces: %s", err) + logger.Fatalf("failed to list workspaces: %s", err) } active, err := workspace.GetActive(dir) if err != nil { - logrus.Fatalf("failed to list workspaces: %s", err) + logger.Fatalf("failed to list workspaces: %s", err) } var activeName string if active != nil { diff --git a/cmd/workspace_new.go b/cmd/workspace_new.go index cc85b25..2e6ac71 100644 --- a/cmd/workspace_new.go +++ b/cmd/workspace_new.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/workspace" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -48,7 +47,7 @@ func init() { func createWorkspace(dir string, name string) { _, err := workspace.New(dir, name) if err != nil { - logrus.Fatalf("failed to create new workspace: %s", err) + logger.Fatalf("failed to create new workspace: %s", err) } - logrus.Infof("created workspace '%s'", name) + logger.Infof("created workspace '%s'", name) } diff --git a/cmd/workspace_select.go b/cmd/workspace_select.go index 7e1bfd3..7d07077 100644 --- a/cmd/workspace_select.go +++ b/cmd/workspace_select.go @@ -18,7 +18,6 @@ package cmd import ( "gatehill.io/imposter/workspace" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "os" ) @@ -48,7 +47,7 @@ func init() { func setActiveWorkspace(dir string, name string) { _, err := workspace.SetActive(dir, name) if err != nil { - logrus.Fatalf("failed to set active workspace: %s", err) + logger.Fatalf("failed to set active workspace: %s", err) } - logrus.Infof("set active workspace to '%s'", name) + logger.Infof("set active workspace to '%s'", name) } diff --git a/config/cli_config.go b/config/cli_config.go index 03aebd5..3ad47b4 100644 --- a/config/cli_config.go +++ b/config/cli_config.go @@ -18,7 +18,7 @@ package config import ( "fmt" - "github.com/sirupsen/logrus" + "gatehill.io/imposter/logging" "os" "path/filepath" ) @@ -31,6 +31,8 @@ type CliConfig struct { // The ConfigFileName is the file name without the file extension. const ConfigFileName = "config" +var logger = logging.GetLogger() + var ( Config CliConfig DirPath string @@ -43,14 +45,6 @@ func init() { } } -func SetLogLevel(lvl string) { - ll, err := logrus.ParseLevel(lvl) - if err != nil { - ll = logrus.DebugLevel - } - logrus.SetLevel(ll) -} - func GetConfigDir() (string, error) { if DirPath != "" { return DirPath, nil diff --git a/config/engine_config.go b/config/engine_config.go index d4c443c..a9c0779 100644 --- a/config/engine_config.go +++ b/config/engine_config.go @@ -17,7 +17,6 @@ limitations under the License. package config import ( - "github.com/sirupsen/logrus" "os" "path/filepath" "strings" @@ -28,7 +27,7 @@ import ( func ContainsConfigFile(configDir string, recursive bool) bool { files, err := os.ReadDir(configDir) if err != nil { - logrus.Errorf("unable to list directory contents: %v: %v", configDir, err) + logger.Errorf("unable to list directory contents: %v: %v", configDir, err) return false } for _, file := range files { diff --git a/engine/builder.go b/engine/builder.go index 0357dbd..c76b071 100644 --- a/engine/builder.go +++ b/engine/builder.go @@ -18,8 +18,8 @@ package engine import ( "fmt" + "gatehill.io/imposter/logging" "gatehill.io/imposter/stringutil" - "github.com/sirupsen/logrus" "github.com/spf13/viper" "os" "strings" @@ -35,6 +35,8 @@ const ( ) const defaultEngineType = EngineTypeDocker +var logger = logging.GetLogger() + var ( libraries = make(map[EngineType]func() EngineLibrary) engines = make(map[EngineType]func(configDir string, startOptions StartOptions) MockEngine) @@ -58,13 +60,13 @@ func EnumerateLibraries() []EngineType { func GetLibrary(engineType EngineType) EngineLibrary { if err := validateEngineType(engineType); err != nil { - logrus.Fatal(err) + logger.Fatal(err) } library := libraries[engineType] if library == nil { - logrus.Fatalf("unregistered engine type: %v", engineType) + logger.Fatalf("unregistered engine type: %v", engineType) } - logrus.Tracef("using %s library", engineType) + logger.Tracef("using %s library", engineType) return library() } @@ -84,13 +86,13 @@ func BuildEngine(engineType EngineType, configDir string, startOptions StartOpti // associated engine builder function. func build(engineType EngineType, configDir string, startOptions StartOptions) MockEngine { if err := validateEngineType(engineType); err != nil { - logrus.Fatal(err) + logger.Fatal(err) } eng := engines[engineType] if eng == nil { - logrus.Fatalf("unregistered engine type: %v", engineType) + logger.Fatalf("unregistered engine type: %v", engineType) } - logrus.Tracef("using %s engine", engineType) + logger.Tracef("using %s engine", engineType) return eng(configDir, startOptions) } diff --git a/engine/docker/engine.go b/engine/docker/engine.go index 2535501..2fe7985 100644 --- a/engine/docker/engine.go +++ b/engine/docker/engine.go @@ -21,6 +21,7 @@ import ( "fmt" "gatehill.io/imposter/debounce" "gatehill.io/imposter/engine" + "gatehill.io/imposter/logging" "gatehill.io/imposter/plugin" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" @@ -43,20 +44,22 @@ const containerPluginDir = "/opt/imposter/plugins" const containerFileCacheDir = "/tmp/imposter-cache" const removalTimeoutSec = 5 +var logger = logging.GetLogger() + func (d *DockerMockEngine) Start(wg *sync.WaitGroup) bool { return d.startWithOptions(wg, d.options) } func (d *DockerMockEngine) startWithOptions(wg *sync.WaitGroup, options engine.StartOptions) (success bool) { - logrus.Infof("starting mock engine on port %d - press ctrl+c to stop", options.Port) + logger.Infof("starting mock engine on port %d - press ctrl+c to stop", options.Port) ctx, cli, err := BuildCliClient() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } if !d.provider.Satisfied() { if err := d.provider.Provide(engine.PullIfNotPresent); err != nil { - logrus.Fatal(err) + logger.Fatal(err) } } @@ -71,7 +74,7 @@ func (d *DockerMockEngine) startWithOptions(wg *sync.WaitGroup, options engine.S // if not specified, falls back to default in container image containerUser := viper.GetString("docker.containerUser") - logrus.Tracef("container user: %s", containerUser) + logger.Tracef("container user: %s", containerUser) resp, err := cli.ContainerCreate(ctx, &container.Config{ Image: d.provider.imageAndTag, @@ -97,19 +100,19 @@ func (d *DockerMockEngine) startWithOptions(wg *sync.WaitGroup, options engine.S }, }, nil, nil, "") if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } containerId := resp.ID d.debouncer.Register(wg, containerId) if err := cli.ContainerStart(ctx, containerId, types.ContainerStartOptions{}); err != nil { - logrus.Fatalf("error starting mock engine container: %v", err) + logger.Fatalf("error starting mock engine container: %v", err) } - logrus.Trace("starting Docker mock engine") + logger.Trace("starting Docker mock engine") d.containerId = containerId if err = streamLogsToStdIo(cli, ctx, containerId); err != nil { - logrus.Warn(err) + logger.Warn(err) } up := engine.WaitUntilUp(options.Port, d.shutDownC) @@ -126,7 +129,7 @@ func buildEnv(options engine.StartOptions) []string { if options.EnableFileCache { env = append(env, "IMPOSTER_CACHE_DIR=/tmp/imposter-cache", "IMPOSTER_OPENAPI_REMOTE_FILE_CACHE=true") } - logrus.Tracef("engine environment: %v", env) + logger.Tracef("engine environment: %v", env) return env } @@ -135,23 +138,23 @@ func buildBinds(d *DockerMockEngine, options engine.StartOptions) []string { d.configDir + ":" + containerConfigDir + viper.GetString("docker.bindFlags"), } if options.EnablePlugins { - logrus.Tracef("plugins are enabled") + logger.Tracef("plugins are enabled") pluginDir, err := plugin.EnsurePluginDir(options.Version) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } binds = append(binds, pluginDir+":"+containerPluginDir) } if options.EnableFileCache { - logrus.Tracef("file cache enabled") + logger.Tracef("file cache enabled") fileCacheDir, err := engine.EnsureFileCacheDir() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } binds = append(binds, fileCacheDir+":"+containerFileCacheDir) } binds = append(binds, parseDirMounts(options.DirMounts)...) - logrus.Tracef("using binds: %v", binds) + logger.Tracef("using binds: %v", binds) return binds } @@ -175,10 +178,10 @@ func parseDirMounts(dirMounts []string) []string { hostDirInfo, err := os.Stat(hostDir) if err != nil { - logrus.Fatalf("failed to stat host dir: %s", hostDir) + logger.Fatalf("failed to stat host dir: %s", hostDir) } if !hostDirInfo.IsDir() { - logrus.Fatalf("host path: %s is not a directory", hostDir) + logger.Fatalf("host path: %s is not a directory", hostDir) } binds = append(binds, mountSpec) } @@ -219,7 +222,7 @@ func streamLogs(cli *client.Client, ctx context.Context, containerId string, out go func() { _, err := stdcopy.StdCopy(outStream, errStream, containerLogs) if err != nil { - logrus.Warnf("error streaming container logs for container with ID: %v: %v", containerId, err) + logger.Warnf("error streaming container logs for container with ID: %v: %v", containerId, err) } }() return nil @@ -241,14 +244,14 @@ func (d *DockerMockEngine) StopImmediately(wg *sync.WaitGroup) { func (d *DockerMockEngine) Stop(wg *sync.WaitGroup) { if len(d.containerId) == 0 { - logrus.Tracef("no container ID to remove") + logger.Tracef("no container ID to remove") wg.Done() return } - if logrus.IsLevelEnabled(logrus.TraceLevel) { - logrus.Tracef("stopping mock engine container %v", d.containerId) + if logger.IsLevelEnabled(logrus.TraceLevel) { + logger.Tracef("stopping mock engine container %v", d.containerId) } else { - logrus.Info("stopping mock engine") + logger.Info("stopping mock engine") } oldContainerId := d.containerId @@ -256,7 +259,7 @@ func (d *DockerMockEngine) Stop(wg *sync.WaitGroup) { // supervisor to work-around removal race go func() { time.Sleep(removalTimeoutSec * time.Second) - logrus.Tracef("fired timeout supervisor for container %v removal", oldContainerId) + logger.Tracef("fired timeout supervisor for container %v removal", oldContainerId) d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: oldContainerId}) }() @@ -278,7 +281,7 @@ func (d *DockerMockEngine) Restart(wg *sync.WaitGroup) { func (d *DockerMockEngine) StopAllManaged() int { cli, ctx, err := BuildCliClient() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } labels := map[string]string{ diff --git a/engine/docker/engine_test.go b/engine/docker/engine_test.go index 267c571..2cabb93 100644 --- a/engine/docker/engine_test.go +++ b/engine/docker/engine_test.go @@ -30,7 +30,7 @@ var engineBuilder = func(tt enginetests.EngineTestScenario) engine.MockEngine { } func init() { - logrus.SetLevel(logrus.TraceLevel) + logger.SetLevel(logrus.TraceLevel) EnableEngine() } @@ -59,7 +59,7 @@ func TestEngine_StartStop(t *testing.T) { } func TestEngine_Restart(t *testing.T) { - logrus.SetLevel(logrus.TraceLevel) + logger.SetLevel(logrus.TraceLevel) workingDir, err := os.Getwd() if err != nil { panic(err) diff --git a/engine/docker/images.go b/engine/docker/images.go index c727d8f..9c0367b 100644 --- a/engine/docker/images.go +++ b/engine/docker/images.go @@ -82,7 +82,7 @@ func ensureContainerImage(cli *client.Client, ctx context.Context, imageTag stri } } if hasImage { - logrus.Debugf("engine image '%v' already present", imageTag) + logger.Debugf("engine image '%v' already present", imageTag) return imageAndTag, nil } } @@ -95,14 +95,14 @@ func ensureContainerImage(cli *client.Client, ctx context.Context, imageTag stri } func pullImage(cli *client.Client, ctx context.Context, imageTag string, imageAndTag string) error { - logrus.Infof("pulling '%v' engine image", imageTag) + logger.Infof("pulling '%v' engine image", imageTag) reader, err := cli.ImagePull(ctx, "docker.io/"+imageAndTag, types.ImagePullOptions{}) if err != nil { return err } var pullLogDestination io.Writer - if logrus.IsLevelEnabled(logrus.TraceLevel) { + if logger.IsLevelEnabled(logrus.TraceLevel) { pullLogDestination = os.Stdout } else { pullLogDestination = ioutil.Discard diff --git a/engine/docker/labels.go b/engine/docker/labels.go index 97555fe..443d4b9 100644 --- a/engine/docker/labels.go +++ b/engine/docker/labels.go @@ -24,7 +24,6 @@ import ( "github.com/docker/docker/api/types" filters2 "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" - "github.com/sirupsen/logrus" ) const labelKeyManaged = "io.gatehill.imposter.managed" @@ -48,11 +47,12 @@ func findContainersWithLabels(cli *client.Client, ctx context.Context, labels ma for key, value := range labels { filters.Add("label", fmt.Sprintf("%v=%v", key, value)) } + cli.Close() containers, err := cli.ContainerList(ctx, types.ContainerListOptions{Filters: filters}) if err != nil { return nil, err } - logrus.Tracef("containers matching labels: %v", containers) + logger.Tracef("containers matching labels: %v", containers) var containerIds []string for _, container := range containers { diff --git a/engine/docker/removal.go b/engine/docker/removal.go index 7e60b42..4923a71 100644 --- a/engine/docker/removal.go +++ b/engine/docker/removal.go @@ -22,12 +22,11 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" - "github.com/sirupsen/logrus" "sync" ) func removeContainers(d *DockerMockEngine, containerIds []string) { - logrus.Tracef("removing containers: %v", containerIds) + logger.Tracef("removing containers: %v", containerIds) wg := &sync.WaitGroup{} for _, containerId := range containerIds { @@ -40,14 +39,14 @@ func removeContainers(d *DockerMockEngine, containerIds []string) { func removeContainer(d *DockerMockEngine, wg *sync.WaitGroup, containerId string) { ctx, cli, err := BuildCliClient() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } // check it exists _, err = cli.ContainerInspect(ctx, containerId) if err != nil { if !client.IsErrNotFound(err) { - logrus.Warnf("failed to find mock engine container %v to remove: %v", containerId, err) + logger.Warnf("failed to find mock engine container %v to remove: %v", containerId, err) d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: containerId, Err: err}) } else { d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: containerId}) @@ -58,7 +57,7 @@ func removeContainer(d *DockerMockEngine, wg *sync.WaitGroup, containerId string err = cli.ContainerRemove(ctx, containerId, types.ContainerRemoveOptions{Force: true}) if err != nil { if !client.IsErrNotFound(err) { - logrus.Warnf("failed to remove mock engine container %v: %v", containerId, err) + logger.Warnf("failed to remove mock engine container %v: %v", containerId, err) d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: containerId, Err: err}) } else { d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: containerId}) @@ -74,14 +73,14 @@ func notifyOnStopBlocking(d *DockerMockEngine, wg *sync.WaitGroup, containerId s select { case err := <-errCh: if err != nil && !client.IsErrNotFound(err) { - logrus.Warnf("failed to wait for mock engine container to stop: %v", err) + logger.Warnf("failed to wait for mock engine container to stop: %v", err) d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: containerId, Err: err}) } else { d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: containerId}) } break case <-statusCh: - logrus.Tracef("mock engine container %v stopped", containerId) + logger.Tracef("mock engine container %v stopped", containerId) d.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: containerId}) break } @@ -94,14 +93,14 @@ func stopDuplicateContainers(d *DockerMockEngine, cli *client.Client, ctx contex func stopContainersWithLabels(d *DockerMockEngine, cli *client.Client, ctx context.Context, containerLabels map[string]string) int { existingContainerIds, err := findContainersWithLabels(cli, ctx, containerLabels) if err != nil { - logrus.Fatalf("error searching for existing containers: %v", err) + logger.Fatalf("error searching for existing containers: %v", err) } if len(existingContainerIds) == 0 { - logrus.Tracef("no existing containers found matching labels: %v", containerLabels) + logger.Tracef("no existing containers found matching labels: %v", containerLabels) return 0 } - logrus.Debugf("stopping %d existing container(s)", len(existingContainerIds)) + logger.Debugf("stopping %d existing container(s)", len(existingContainerIds)) removeContainers(d, existingContainerIds) return len(existingContainerIds) } diff --git a/engine/file_cache.go b/engine/file_cache.go index 129197b..d895c3b 100644 --- a/engine/file_cache.go +++ b/engine/file_cache.go @@ -2,7 +2,6 @@ package engine import ( "gatehill.io/imposter/library" - "github.com/sirupsen/logrus" ) const fileCacheDir = ".imposter/filecache/" @@ -13,6 +12,6 @@ func EnsureFileCacheDir() (string, error) { if err != nil { return "", err } - logrus.Tracef("ensured file cache directory: %v", fileCacheDir) + logger.Tracef("ensured file cache directory: %v", fileCacheDir) return fileCacheDir, nil } diff --git a/engine/health.go b/engine/health.go index 8d6dd66..f643f31 100644 --- a/engine/health.go +++ b/engine/health.go @@ -18,7 +18,6 @@ package engine import ( "fmt" - "github.com/sirupsen/logrus" "github.com/spf13/viper" "io" "net/http" @@ -37,7 +36,7 @@ func getStartTimeout() time.Duration { func WaitUntilUp(port int, shutDownC chan bool) (success bool) { url := fmt.Sprintf("http://localhost:%d/system/status", port) - logrus.Tracef("waiting for mock engine to come up at %v", url) + logger.Tracef("waiting for mock engine to come up at %v", url) startedC := make(chan bool) max := time.NewTimer(getStartTimeout()) @@ -65,15 +64,15 @@ func WaitUntilUp(port int, shutDownC chan bool) (success bool) { select { case <-max.C: finished = true - logrus.Fatalf("timed out waiting for engine to start: could not reach status endpoint: %s", url) + logger.Fatalf("timed out waiting for engine to start: could not reach status endpoint: %s", url) return false case <-startedC: finished = true - logrus.Tracef("engine started") + logger.Tracef("engine started") return true case <-shutDownC: if !finished { - logrus.Debugf("aborted health probe") + logger.Debugf("aborted health probe") } return false } diff --git a/engine/jvm/engine.go b/engine/jvm/engine.go index 795a1e6..1f29776 100644 --- a/engine/jvm/engine.go +++ b/engine/jvm/engine.go @@ -20,6 +20,7 @@ import ( "fmt" "gatehill.io/imposter/debounce" "gatehill.io/imposter/engine" + "gatehill.io/imposter/logging" "gatehill.io/imposter/plugin" "github.com/sirupsen/logrus" "os" @@ -28,13 +29,15 @@ import ( "sync" ) +var logger = logging.GetLogger() + func (j *JvmMockEngine) Start(wg *sync.WaitGroup) bool { return j.startWithOptions(wg, j.options) } func (j *JvmMockEngine) startWithOptions(wg *sync.WaitGroup, options engine.StartOptions) (success bool) { if len(options.DirMounts) > 0 { - logrus.Warnf("JVM engine does not support directory mounts - these will be ignored") + logger.Warnf("JVM engine does not support directory mounts - these will be ignored") } args := []string{ @@ -47,10 +50,10 @@ func (j *JvmMockEngine) startWithOptions(wg *sync.WaitGroup, options engine.Star command.Stderr = os.Stderr err := command.Start() if err != nil { - logrus.Fatalf("failed to exec: %v %v: %v", command.Path, command.Args, err) + logger.Fatalf("failed to exec: %v %v: %v", command.Path, command.Args, err) } j.debouncer.Register(wg, strconv.Itoa(command.Process.Pid)) - logrus.Trace("starting JVM mock engine") + logger.Trace("starting JVM mock engine") j.command = command up := engine.WaitUntilUp(options.Port, j.shutDownC) @@ -66,22 +69,22 @@ func (j *JvmMockEngine) startWithOptions(wg *sync.WaitGroup, options engine.Star func buildEnv(options engine.StartOptions) []string { env := engine.BuildEnv(options, true) if options.EnablePlugins { - logrus.Tracef("plugins are enabled") + logger.Tracef("plugins are enabled") pluginDir, err := plugin.EnsurePluginDir(options.Version) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } env = append(env, "IMPOSTER_PLUGIN_DIR="+pluginDir) } if options.EnableFileCache { - logrus.Tracef("file cache enabled") + logger.Tracef("file cache enabled") fileCacheDir, err := engine.EnsureFileCacheDir() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } env = append(env, "IMPOSTER_CACHE_DIR="+fileCacheDir, "IMPOSTER_OPENAPI_REMOTE_FILE_CACHE=true") } - logrus.Tracef("engine environment: %v", env) + logger.Tracef("engine environment: %v", env) return env } @@ -92,19 +95,19 @@ func (j *JvmMockEngine) StopImmediately(wg *sync.WaitGroup) { func (j *JvmMockEngine) Stop(wg *sync.WaitGroup) { if j.command == nil { - logrus.Tracef("no process to remove") + logger.Tracef("no process to remove") wg.Done() return } - if logrus.IsLevelEnabled(logrus.TraceLevel) { - logrus.Tracef("stopping mock engine with PID: %v", j.command.Process.Pid) + if logger.IsLevelEnabled(logrus.TraceLevel) { + logger.Tracef("stopping mock engine with PID: %v", j.command.Process.Pid) } else { - logrus.Info("stopping mock engine") + logger.Info("stopping mock engine") } err := j.command.Process.Kill() if err != nil { - logrus.Fatalf("error stopping engine with PID: %d: %v", j.command.Process.Pid, err) + logger.Fatalf("error stopping engine with PID: %d: %v", j.command.Process.Pid, err) } j.notifyOnStopBlocking(wg) } @@ -123,12 +126,12 @@ func (j *JvmMockEngine) Restart(wg *sync.WaitGroup) { func (j *JvmMockEngine) notifyOnStopBlocking(wg *sync.WaitGroup) { if j.command == nil || j.command.Process == nil { - logrus.Trace("no subprocess - notifying immediately") + logger.Trace("no subprocess - notifying immediately") j.debouncer.Notify(wg, debounce.AtMostOnceEvent{}) } pid := strconv.Itoa(j.command.Process.Pid) if j.command.ProcessState != nil && j.command.ProcessState.Exited() { - logrus.Tracef("process with PID: %v already exited - notifying immediately", pid) + logger.Tracef("process with PID: %v already exited - notifying immediately", pid) j.debouncer.Notify(wg, debounce.AtMostOnceEvent{Id: pid}) } _, err := j.command.Process.Wait() @@ -145,21 +148,21 @@ func (j *JvmMockEngine) notifyOnStopBlocking(wg *sync.WaitGroup) { func (j *JvmMockEngine) StopAllManaged() int { processes, err := findImposterJvmProcesses() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } if len(processes) == 0 { return 0 } for _, pid := range processes { - logrus.Tracef("finding JVM process to kill with PID: %d", pid) + logger.Tracef("finding JVM process to kill with PID: %d", pid) p, err := os.FindProcess(pid) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } - logrus.Debugf("killing JVM process with PID: %d", pid) + logger.Debugf("killing JVM process with PID: %d", pid) err = p.Kill() if err != nil { - logrus.Warnf("error killing JVM process with PID: %d: %v", pid, err) + logger.Warnf("error killing JVM process with PID: %d: %v", pid, err) } } return len(processes) diff --git a/engine/jvm/engine_test.go b/engine/jvm/engine_test.go index c853661..e178c3b 100644 --- a/engine/jvm/engine_test.go +++ b/engine/jvm/engine_test.go @@ -30,7 +30,7 @@ var engineBuilder = func(tt enginetests.EngineTestScenario) engine.MockEngine { } func init() { - logrus.SetLevel(logrus.TraceLevel) + logger.SetLevel(logrus.TraceLevel) EnableSingleJarEngine() EnableUnpackedDistroEngine() } @@ -60,7 +60,7 @@ func TestEngine_StartStop(t *testing.T) { } func TestEngine_Restart(t *testing.T) { - logrus.SetLevel(logrus.TraceLevel) + logger.SetLevel(logrus.TraceLevel) workingDir, err := os.Getwd() if err != nil { panic(err) diff --git a/engine/jvm/java.go b/engine/jvm/java.go index 3c48b19..a58c575 100644 --- a/engine/jvm/java.go +++ b/engine/jvm/java.go @@ -2,7 +2,6 @@ package jvm import ( "fmt" - "github.com/sirupsen/logrus" "os" "os/exec" "path/filepath" @@ -16,7 +15,7 @@ func GetJavaCmdPath() (string, error) { // search for 'java' in the PATH javaPath, err := exec.LookPath("java") if err != nil { - logrus.Tracef("could not find 'java' in PATH: %s", err) + logger.Tracef("could not find 'java' in PATH: %s", err) } var binaryPathSuffix string @@ -51,6 +50,6 @@ func GetJavaCmdPath() (string, error) { return "", fmt.Errorf("failed to determine Java path - consider setting JAVA_HOME or updating PATH") } - logrus.Tracef("using java: %v", javaPath) + logger.Tracef("using java: %v", javaPath) return javaPath, nil } diff --git a/engine/jvm/processes.go b/engine/jvm/processes.go index 24add48..0cc30e0 100644 --- a/engine/jvm/processes.go +++ b/engine/jvm/processes.go @@ -3,7 +3,6 @@ package jvm import ( "fmt" "github.com/shirou/gopsutil/v3/process" - "github.com/sirupsen/logrus" "regexp" ) @@ -30,7 +29,7 @@ func findImposterJvmProcesses() ([]int, error) { if !isImposter { continue } - logrus.Tracef("found JVM Imposter process %d: %v", p.Pid, cmdline) + logger.Tracef("found JVM Imposter process %d: %v", p.Pid, cmdline) imposterPids = append(imposterPids, int(p.Pid)) } return imposterPids, nil diff --git a/engine/jvm/single_jar.go b/engine/jvm/single_jar.go index 0ccbcae..a1784b5 100644 --- a/engine/jvm/single_jar.go +++ b/engine/jvm/single_jar.go @@ -4,7 +4,6 @@ import ( "fmt" "gatehill.io/imposter/engine" "gatehill.io/imposter/library" - "github.com/sirupsen/logrus" "github.com/spf13/viper" "os" "os/exec" @@ -59,13 +58,13 @@ func (p *SingleJarProvider) GetStartCommand(args []string, env []string) *exec.C if p.javaCmd == "" { javaCmd, err := GetJavaCmdPath() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } p.javaCmd = javaCmd } if !p.Satisfied() { if err := p.Provide(engine.PullIfNotPresent); err != nil { - logrus.Fatal(err) + logger.Fatal(err) } } allArgs := append( @@ -95,7 +94,7 @@ func ensureBinary(version string, policy engine.PullPolicy) (string, error) { if _, err := os.Stat(envJarFile); err != nil { return "", fmt.Errorf("could not stat JAR file: %v: %v", envJarFile, err) } - logrus.Debugf("using JAR file: %v", envJarFile) + logger.Debugf("using JAR file: %v", envJarFile) return envJarFile, nil } return checkOrDownloadBinary(version, policy) @@ -104,7 +103,7 @@ func ensureBinary(version string, policy engine.PullPolicy) (string, error) { func checkOrDownloadBinary(version string, policy engine.PullPolicy) (string, error) { binCachePath, err := ensureBinCache() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } binFilePath := filepath.Join(binCachePath, fmt.Sprintf("imposter-%v.jar", version)) @@ -118,8 +117,8 @@ func checkOrDownloadBinary(version string, policy engine.PullPolicy) (string, er return "", fmt.Errorf("failed to stat: %v: %v", binFilePath, err) } } else { - logrus.Debugf("engine binary '%v' already present", version) - logrus.Tracef("binary for version %v found at: %v", version, binFilePath) + logger.Debugf("engine binary '%v' already present", version) + logger.Tracef("binary for version %v found at: %v", version, binFilePath) return binFilePath, nil } } @@ -127,7 +126,7 @@ func checkOrDownloadBinary(version string, policy engine.PullPolicy) (string, er if err := downloadBinary(binFilePath, version); err != nil { return "", fmt.Errorf("failed to fetch binary: %v", err) } - logrus.Tracef("using imposter at: %v", binFilePath) + logger.Tracef("using imposter at: %v", binFilePath) return binFilePath, nil } diff --git a/engine/jvm/unpacked_distro.go b/engine/jvm/unpacked_distro.go index a88773c..6618d75 100644 --- a/engine/jvm/unpacked_distro.go +++ b/engine/jvm/unpacked_distro.go @@ -3,7 +3,6 @@ package jvm import ( "fmt" "gatehill.io/imposter/engine" - "github.com/sirupsen/logrus" "github.com/spf13/viper" "os" "os/exec" @@ -53,13 +52,13 @@ func (p *UnpackedDistroProvider) GetStartCommand(args []string, env []string) *e if p.javaCmd == "" { javaCmd, err := GetJavaCmdPath() if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } p.javaCmd = javaCmd } if !p.Satisfied() { if err := p.Provide(engine.PullIfNotPresent); err != nil { - logrus.Fatal(err) + logger.Fatal(err) } } allArgs := append( @@ -80,7 +79,7 @@ func (p *UnpackedDistroProvider) Provide(engine.PullPolicy) error { } else if !fileInfo.IsDir() { return fmt.Errorf("distribution path is not a directory: %v", envDistroDir) } - logrus.Debugf("using distribution at: %v", envDistroDir) + logger.Debugf("using distribution at: %v", envDistroDir) p.distroDir = envDistroDir return nil } diff --git a/engine/version.go b/engine/version.go index 31ad4ed..93e1725 100644 --- a/engine/version.go +++ b/engine/version.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "gatehill.io/imposter/prefs" - "github.com/sirupsen/logrus" "io/ioutil" "net/http" "strings" @@ -15,7 +14,7 @@ const latestReleaseApi = "https://api.github.com/repos/outofcoffee/imposter/rele const checkThresholdSeconds = 86_400 func ResolveLatestToVersion(allowCached bool) (string, error) { - logrus.Tracef("resolving latest version (cache allowed: %v)", allowCached) + logger.Tracef("resolving latest version (cache allowed: %v)", allowCached) now := time.Now().Unix() var latest string @@ -32,7 +31,7 @@ func ResolveLatestToVersion(allowCached bool) (string, error) { latest = lookup } - logrus.Tracef("resolved latest version: %s", latest) + logger.Tracef("resolved latest version: %s", latest) return latest, nil } @@ -45,7 +44,7 @@ func loadCached(now int64) string { latest, _ = p.ReadPropertyString("latest") } - logrus.Tracef("latest version cached value: %s", latest) + logger.Tracef("latest version cached value: %s", latest) return latest } @@ -56,7 +55,7 @@ func lookupLatest(now int64, allowFallbackToCached bool) (string, error) { return "", fmt.Errorf("failed to fetch latest version from API: %s", err) } - logrus.Warnf("failed to fetch latest version from API (%s) - checking cache", err) + logger.Warnf("failed to fetch latest version from API (%s) - checking cache", err) latest = loadCached(now) if latest == "" { return "", fmt.Errorf("failed to resolve latest version (%s) and no cached version found", err) @@ -69,11 +68,11 @@ func lookupLatest(now int64, allowFallbackToCached bool) (string, error) { p := getVersionPrefs() err = p.WriteProperty("latest", latest) if err != nil { - logrus.Warnf("failed to record latest version: %s", err) + logger.Warnf("failed to record latest version: %s", err) } err = p.WriteProperty("last_version_check", now) if err != nil { - logrus.Warnf("failed to record last version check time: %s", err) + logger.Warnf("failed to record last version check time: %s", err) } return latest, nil } @@ -83,7 +82,7 @@ func getVersionPrefs() prefs.Prefs { } func fetchLatestFromApi() (string, error) { - logrus.Tracef("fetching latest version from: %s", latestReleaseApi) + logger.Tracef("fetching latest version from: %s", latestReleaseApi) resp, err := http.Get(latestReleaseApi) if err != nil { return "", fmt.Errorf("failed to determine latest version from %s: %s", latestReleaseApi, err) diff --git a/fileutil/dirwatcher.go b/fileutil/dirwatcher.go index 5086039..a23bc25 100644 --- a/fileutil/dirwatcher.go +++ b/fileutil/dirwatcher.go @@ -18,7 +18,6 @@ package fileutil import ( "github.com/radovskyb/watcher" - "github.com/sirupsen/logrus" "time" ) @@ -31,19 +30,19 @@ func WatchDir(dir string) (updatedC chan bool) { w := watcher.New() if err := w.AddRecursive(dir); err != nil { - logrus.Warnln(err) + logger.Warnln(err) } dirUpdated := false go func() { - logrus.Infof("watching for changes to: %v", dir) + logger.Infof("watching for changes to: %v", dir) for { select { case <-w.Event: dirUpdated = true break case err := <-w.Error: - logrus.Warnln(err) + logger.Warnln(err) case <-w.Closed: return } @@ -52,7 +51,7 @@ func WatchDir(dir string) (updatedC chan bool) { go func() { if err := w.Start(time.Millisecond * 500); err != nil { - logrus.Warnln(err) + logger.Warnln(err) } }() diff --git a/fileutil/fileutil.go b/fileutil/fileutil.go index ebb1373..09dbc9c 100644 --- a/fileutil/fileutil.go +++ b/fileutil/fileutil.go @@ -18,7 +18,7 @@ package fileutil import ( "fmt" - "github.com/sirupsen/logrus" + "gatehill.io/imposter/logging" "io" "io/ioutil" "os" @@ -26,11 +26,13 @@ import ( "strings" ) +var logger = logging.GetLogger() + func FindFilesWithExtension(dir, ext string) []string { var filesWithExtension []string infos, err := ioutil.ReadDir(dir) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } for _, info := range infos { if !info.IsDir() && filepath.Ext(info.Name()) == ext { @@ -46,10 +48,10 @@ func GenerateFilePathAdjacentToFile(sourceFilePath string, suffix string, forceO destFilePath := strings.TrimSuffix(sourceFilePath, filepath.Ext(sourceFilePath)) + suffix if _, err := os.Stat(destFilePath); err != nil { if !os.IsNotExist(err) { - logrus.Fatal(err) + logger.Fatal(err) } } else if !forceOverwrite { - logrus.Fatalf("file already exists: %v - aborting", destFilePath) + logger.Fatalf("file already exists: %v - aborting", destFilePath) } return destFilePath } diff --git a/impostermodel/configfile.go b/impostermodel/configfile.go index 93dbe80..967d0e0 100644 --- a/impostermodel/configfile.go +++ b/impostermodel/configfile.go @@ -18,15 +18,17 @@ package impostermodel import ( "gatehill.io/imposter/fileutil" + "gatehill.io/imposter/logging" "gatehill.io/imposter/openapi" - "github.com/sirupsen/logrus" "os" "path/filepath" ) +var logger = logging.GetLogger() + func CreateFromSpecs(configDir string, generateResources bool, forceOverwrite bool, scriptEngine ScriptEngine) { openApiSpecs := openapi.DiscoverOpenApiSpecs(configDir) - logrus.Infof("found %d OpenAPI spec(s)", len(openApiSpecs)) + logger.Infof("found %d OpenAPI spec(s)", len(openApiSpecs)) for _, openApiSpec := range openApiSpecs { writeMockConfig(openApiSpec, generateResources, forceOverwrite, scriptEngine) @@ -44,7 +46,7 @@ func writeMockConfig(specFilePath string, generateResources bool, forceOverwrite if generateResources { resources = buildResources(specFilePath, scriptEngine, scriptFileName) } else { - logrus.Debug("skipping resource generation") + logger.Debug("skipping resource generation") } config := GenerateConfig(specFilePath, resources, ConfigGenerationOptions{ @@ -55,22 +57,22 @@ func writeMockConfig(specFilePath string, generateResources bool, forceOverwrite configFilePath := fileutil.GenerateFilePathAdjacentToFile(specFilePath, "-config.yaml", forceOverwrite) configFile, err := os.Create(configFilePath) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } defer configFile.Close() _, err = configFile.Write(config) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } - logrus.Infof("wrote Imposter config: %v", configFilePath) + logger.Infof("wrote Imposter config: %v", configFilePath) } func writeScriptFile(specFilePath string, engine ScriptEngine, forceOverwrite bool) string { scriptFilePath := BuildScriptFilePath(specFilePath, engine, forceOverwrite) scriptFile, err := os.Create(scriptFilePath) if err != nil { - logrus.Fatalf("error writing script file: %v: %v", scriptFilePath, err) + logger.Fatalf("error writing script file: %v: %v", scriptFilePath, err) } defer scriptFile.Close() @@ -83,10 +85,10 @@ logger.debug('queryParams: ' + context.request.queryParams); logger.debug('headers: ' + context.request.headers); `) if err != nil { - logrus.Fatalf("error writing script file: %v: %v", scriptFilePath, err) + logger.Fatalf("error writing script file: %v: %v", scriptFilePath, err) } - logrus.Infof("wrote script file: %v", scriptFilePath) + logger.Infof("wrote script file: %v", scriptFilePath) return scriptFilePath } @@ -95,6 +97,6 @@ func buildResources(specFilePath string, scriptEngine ScriptEngine, scriptFileNa ScriptEngine: scriptEngine, ScriptFileName: scriptFileName, }) - logrus.Debugf("generated %d resources from spec", len(resources)) + logger.Debugf("generated %d resources from spec", len(resources)) return resources } diff --git a/impostermodel/generator.go b/impostermodel/generator.go index 5a5aa24..efce848 100644 --- a/impostermodel/generator.go +++ b/impostermodel/generator.go @@ -18,7 +18,6 @@ package impostermodel import ( "gatehill.io/imposter/openapi" - "github.com/sirupsen/logrus" "path/filepath" "sigs.k8s.io/yaml" "strings" @@ -51,7 +50,7 @@ func GenerateConfig(specFilePath string, resources []Resource, options ConfigGen config, err := yaml.Marshal(pluginConfig) if err != nil { - logrus.Fatalf("unable to marshal imposter config: %v", err) + logger.Fatalf("unable to marshal imposter config: %v", err) } return config } @@ -60,7 +59,7 @@ func GenerateResourcesFromSpec(specFilePath string, options ResourceGenerationOp var resources []Resource partialSpec, err := openapi.Parse(specFilePath) if err != nil { - logrus.Fatalf("unable to parse openapi spec: %v: %v", specFilePath, err) + logger.Fatalf("unable to parse openapi spec: %v: %v", specFilePath, err) } if partialSpec != nil { for path, pathDetail := range partialSpec.Paths { diff --git a/impostermodel/scripting.go b/impostermodel/scripting.go index 23b0a27..afc5e6d 100644 --- a/impostermodel/scripting.go +++ b/impostermodel/scripting.go @@ -19,7 +19,6 @@ package impostermodel import ( "fmt" "gatehill.io/imposter/fileutil" - "github.com/sirupsen/logrus" ) type ScriptEngine string @@ -59,7 +58,7 @@ func BuildScriptFilePath(specFilePath string, scriptEngine ScriptEngine, forceOv scriptEngineExt = ".groovy" break default: - logrus.Fatal("script engine is disabled") + logger.Fatal("script engine is disabled") } scriptFilePath = fileutil.GenerateFilePathAdjacentToFile(specFilePath, scriptEngineExt, forceOverwrite) } diff --git a/library/fetch.go b/library/fetch.go index dac2ea8..e4440cb 100644 --- a/library/fetch.go +++ b/library/fetch.go @@ -2,7 +2,6 @@ package library import ( "fmt" - "github.com/sirupsen/logrus" "io" "net/http" "os" @@ -16,7 +15,7 @@ func DownloadBinary(localPath string, remoteFileName string, version string) err } func DownloadBinaryWithFallback(localPath string, remoteFileName string, version string, fallbackRemoteFileName string) error { - logrus.Tracef("attempting to download %s version %s to %s", remoteFileName, version, localPath) + logger.Tracef("attempting to download %s version %s to %s", remoteFileName, version, localPath) file, err := os.Create(localPath) if err != nil { return fmt.Errorf("error creating file: %v: %v", localPath, err) @@ -24,7 +23,7 @@ func DownloadBinaryWithFallback(localPath string, remoteFileName string, version defer func() { _ = file.Close() if stat, err := os.Stat(localPath); err == nil && stat.Size() == 0 { - logrus.Tracef("removing empty file: %s", localPath) + logger.Tracef("removing empty file: %s", localPath) _ = os.Remove(localPath) } }() @@ -49,7 +48,7 @@ func DownloadBinaryWithFallback(localPath string, remoteFileName string, version // fallback to versioned binary filename if resp.StatusCode == 404 && fallbackRemoteFileName != "" { - logrus.Tracef("binary not found at: %v - retrying with fallback filename", url) + logger.Tracef("binary not found at: %v - retrying with fallback filename", url) url = versionedBaseUrl + fallbackRemoteFileName resp, err = makeHttpRequest(url, err) if err != nil { @@ -67,7 +66,7 @@ func DownloadBinaryWithFallback(localPath string, remoteFileName string, version } func makeHttpRequest(url string, err error) (*http.Response, error) { - logrus.Debugf("downloading %v", url) + logger.Debugf("downloading %v", url) resp, err := http.Get(url) if err != nil { return nil, fmt.Errorf("error downloading from: %v: %v", url, err) diff --git a/library/local.go b/library/local.go index 2656aeb..c59b6fc 100644 --- a/library/local.go +++ b/library/local.go @@ -2,12 +2,14 @@ package library import ( "fmt" - "github.com/sirupsen/logrus" + "gatehill.io/imposter/logging" "github.com/spf13/viper" "os" "path/filepath" ) +var logger = logging.GetLogger() + func EnsureDirUsingConfig(settingsKey string, homeSubDirPath string) (string, error) { dirPath, err := GetDirPath(settingsKey, homeSubDirPath) if err != nil { @@ -17,7 +19,7 @@ func EnsureDirUsingConfig(settingsKey string, homeSubDirPath string) (string, er if err != nil { return "", err } - logrus.Tracef("ensured directory: %v", dirPath) + logger.Tracef("ensured directory: %v", dirPath) return dirPath, nil } @@ -35,7 +37,7 @@ func GetDirPath(settingsKey string, homeSubDirPath string) (string, error) { func EnsureDir(dirPath string) error { if info, err := os.Stat(dirPath); err != nil { if os.IsNotExist(err) { - logrus.Tracef("creating directory: %v", dirPath) + logger.Tracef("creating directory: %v", dirPath) err := os.MkdirAll(dirPath, 0700) if err != nil { return fmt.Errorf("failed to create directory: %v: %v", dirPath, err) diff --git a/logging/logger.go b/logging/logger.go new file mode 100644 index 0000000..16e38dc --- /dev/null +++ b/logging/logger.go @@ -0,0 +1,21 @@ +package logging + +import "github.com/sirupsen/logrus" + +var logger = logrus.New() + +func SetLogLevel(lvl string) { + // quieten the default logger + logrus.SetLevel(logrus.InfoLevel) + + ll, err := logrus.ParseLevel(lvl) + if err != nil { + ll = logrus.DebugLevel + } + logger.SetLevel(ll) +} + +// GetLogger returns the configured logger. +func GetLogger() *logrus.Logger { + return logger +} diff --git a/main.go b/main.go index 2da77c5..d1adc00 100644 --- a/main.go +++ b/main.go @@ -21,6 +21,7 @@ import ( "gatehill.io/imposter/config" "gatehill.io/imposter/engine/docker" "gatehill.io/imposter/engine/jvm" + "gatehill.io/imposter/logging" "gatehill.io/imposter/remote/cloudmocks" "gatehill.io/imposter/stringutil" "os" @@ -32,7 +33,7 @@ var version string func main() { lvl := stringutil.GetFirstNonEmpty(os.Getenv("LOG_LEVEL"), os.Getenv("IMPOSTER_CLI_LOG_LEVEL"), defaultLogLevel) - config.SetLogLevel(lvl) + logging.SetLogLevel(lvl) if version == "" { version = "dev" diff --git a/openapi/discovery.go b/openapi/discovery.go index ed6cb80..761ad98 100644 --- a/openapi/discovery.go +++ b/openapi/discovery.go @@ -20,12 +20,14 @@ import ( "encoding/json" "fmt" "gatehill.io/imposter/fileutil" - "github.com/sirupsen/logrus" + "gatehill.io/imposter/logging" "io/ioutil" "path/filepath" "sigs.k8s.io/yaml" ) +var logger = logging.GetLogger() + // DiscoverOpenApiSpecs finds JSON and YAML OpenAPI specification files // within the given directory. It returns fully qualified paths // to the files discovered. @@ -36,7 +38,7 @@ func DiscoverOpenApiSpecs(configDir string) []string { fullyQualifiedPath := filepath.Join(configDir, yamlFile) jsonContent, err := loadYamlAsJson(fullyQualifiedPath) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } if isOpenApiSpec(jsonContent) { openApiSpecs = append(openApiSpecs, fullyQualifiedPath) @@ -47,7 +49,7 @@ func DiscoverOpenApiSpecs(configDir string) []string { fullyQualifiedPath := filepath.Join(configDir, jsonFile) jsonContent, err := ioutil.ReadFile(fullyQualifiedPath) if err != nil { - logrus.Fatal(err) + logger.Fatal(err) } if isOpenApiSpec(jsonContent) { openApiSpecs = append(openApiSpecs, fullyQualifiedPath) diff --git a/openapi/parser.go b/openapi/parser.go index a20b975..8506e31 100644 --- a/openapi/parser.go +++ b/openapi/parser.go @@ -18,7 +18,6 @@ package openapi import ( "fmt" - "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" "io/ioutil" "os" @@ -50,6 +49,6 @@ func Parse(specFile string) (*PartialModel, error) { return nil, fmt.Errorf("error: %v\n", err) } - logrus.Tracef("openapi parsed:\n%v\n\n", o) + logger.Tracef("openapi parsed:\n%v\n\n", o) return &o, nil } diff --git a/plugin/plugin.go b/plugin/plugin.go index 4df6dbd..5865308 100644 --- a/plugin/plugin.go +++ b/plugin/plugin.go @@ -4,8 +4,8 @@ import ( "fmt" "gatehill.io/imposter/config" "gatehill.io/imposter/library" + "gatehill.io/imposter/logging" "gatehill.io/imposter/stringutil" - "github.com/sirupsen/logrus" "github.com/spf13/viper" "os" "path/filepath" @@ -14,8 +14,10 @@ import ( const pluginBaseDir = ".imposter/plugins/" +var logger = logging.GetLogger() + func EnsurePlugins(plugins []string, version string, saveDefault bool) (int, error) { - logrus.Tracef("ensuring %d plugins: %v", len(plugins), plugins) + logger.Tracef("ensuring %d plugins: %v", len(plugins), plugins) if len(plugins) == 0 { return 0, nil } @@ -24,12 +26,12 @@ func EnsurePlugins(plugins []string, version string, saveDefault bool) (int, err if err != nil { return 0, fmt.Errorf("error ensuring plugin %s: %s", plugin, err) } - logrus.Debugf("plugin %s version %s is installed", plugin, version) + logger.Debugf("plugin %s version %s is installed", plugin, version) } if saveDefault { err := addDefaultPlugins(plugins) if err != nil { - logrus.Warnf("error setting plugins as default: %s", err) + logger.Warnf("error setting plugins as default: %s", err) } } return len(plugins), nil @@ -54,7 +56,7 @@ func EnsureDefaultPlugins(version string) (int, error) { } } - logrus.Tracef("found %d default plugin(s): %v", len(plugins), plugins) + logger.Tracef("found %d default plugin(s): %v", len(plugins), plugins) return EnsurePlugins(plugins, version, false) } @@ -68,10 +70,10 @@ func EnsurePlugin(pluginName string, version string) error { return fmt.Errorf("unable to stat plugin file: %s: %s", pluginFilePath, err) } } else { - logrus.Tracef("plugin %s version %s already exists at: %s", pluginName, version, pluginFilePath) + logger.Tracef("plugin %s version %s already exists at: %s", pluginName, version, pluginFilePath) return nil } - logrus.Debugf("plugin %s version %s is not installed", pluginName, version) + logger.Debugf("plugin %s version %s is not installed", pluginName, version) err = downloadPlugin(pluginName, version) if err != nil { return err @@ -88,7 +90,7 @@ func EnsurePluginDir(version string) (string, error) { if err != nil { return "", err } - logrus.Tracef("ensured plugin directory: %v", fullPluginDir) + logger.Tracef("ensured plugin directory: %v", fullPluginDir) return fullPluginDir, nil } @@ -114,7 +116,7 @@ func downloadPlugin(pluginName string, version string) error { if err != nil { return err } - logrus.Infof("downloaded plugin %s version %s", pluginName, version) + logger.Infof("downloaded plugin %s version %s", pluginName, version) return nil } @@ -170,7 +172,7 @@ func writeDefaultPlugins(plugins []string) error { return fmt.Errorf("error writing default plugin configuration to: %s: %s", configFilePath, err) } - logrus.Tracef("wrote default plugin configuration to: %s", configFilePath) + logger.Tracef("wrote default plugin configuration to: %s", configFilePath) return nil } diff --git a/plugin/plugin_test.go b/plugin/plugin_test.go index 660d63f..07e3a53 100644 --- a/plugin/plugin_test.go +++ b/plugin/plugin_test.go @@ -8,7 +8,7 @@ import ( ) func init() { - logrus.SetLevel(logrus.TraceLevel) + logger.SetLevel(logrus.TraceLevel) } func TestEnsurePluginDir(t *testing.T) { diff --git a/remote/cloudmocks/config.go b/remote/cloudmocks/config.go index d968e52..56e1a2e 100644 --- a/remote/cloudmocks/config.go +++ b/remote/cloudmocks/config.go @@ -3,6 +3,7 @@ package cloudmocks import ( "encoding/json" "fmt" + "gatehill.io/imposter/logging" "gatehill.io/imposter/prefs" "gatehill.io/imposter/remote" "gatehill.io/imposter/workspace" @@ -25,6 +26,8 @@ type config struct { Url string `json:"url"` } +var logger = logging.GetLogger() + func Register() { remote.Register(remoteType, func(dir string, workspace *workspace.Workspace) (remote.Remote, error) { return Load(dir, workspace) diff --git a/remote/cloudmocks/deploy.go b/remote/cloudmocks/deploy.go index a4dbcab..a4b0cca 100644 --- a/remote/cloudmocks/deploy.go +++ b/remote/cloudmocks/deploy.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "gatehill.io/imposter/remote" - "github.com/sirupsen/logrus" "io" "io/ioutil" "mime/multipart" @@ -72,7 +71,7 @@ func (m Remote) Deploy() (*remote.EndpointDetails, error) { func (m Remote) ensureMockExists() error { if m.config.MockId == "" { - logrus.Debugf("creating new mock") + logger.Debugf("creating new mock") var resp createMockResponse err := m.request("POST", "/api/mocks", &resp) @@ -80,7 +79,7 @@ func (m Remote) ensureMockExists() error { return fmt.Errorf("failed to create mock: %s", err) } - logrus.Debugf("created mock with ID: %s", resp.MockId) + logger.Debugf("created mock with ID: %s", resp.MockId) m.config.MockId = resp.MockId err = m.saveConfig() if err != nil { @@ -88,19 +87,19 @@ func (m Remote) ensureMockExists() error { } } else { - logrus.Debugf("using existing mock with ID: %s", m.config.MockId) + logger.Debugf("using existing mock with ID: %s", m.config.MockId) } return nil } func (m Remote) setMockState(state string) error { - logrus.Debugf("setting mock state to: %s", state) + logger.Debugf("setting mock state to: %s", state) var resp interface{} err := m.request("PATCH", fmt.Sprintf("/api/mocks/%s/state/%s", m.config.MockId, state), &resp) if err != nil { return fmt.Errorf("failed to set mock state to: %s: %s", state, err) } - logrus.Infof("set mock state to: %s", state) + logger.Infof("set mock state to: %s", state) return nil } @@ -123,7 +122,7 @@ func (m Remote) getEndpoint() (*getEndpointResponse, error) { } func (m Remote) waitForStatus(s string, shutDownC chan bool) bool { - logrus.Infof("waiting for mock status to be: %s...", s) + logger.Infof("waiting for mock status to be: %s...", s) finishedC := make(chan bool) max := time.NewTimer(120 * time.Second) @@ -136,7 +135,7 @@ func (m Remote) waitForStatus(s string, shutDownC chan bool) bool { if err != nil { continue } - logrus.Tracef("mock status: %v", status.Status) + logger.Tracef("mock status: %v", status.Status) if status.Status == s { finishedC <- true break @@ -150,15 +149,15 @@ func (m Remote) waitForStatus(s string, shutDownC chan bool) bool { select { case <-max.C: finished = true - logrus.Fatalf("timed out waiting for mock status to be: %s", s) + logger.Fatalf("timed out waiting for mock status to be: %s", s) return false case success := <-finishedC: finished = success - logrus.Tracef("finished probe with desired mock status: %v", success) + logger.Tracef("finished probe with desired mock status: %v", success) return success case <-shutDownC: if !finished { - logrus.Debugf("aborted status probe") + logger.Debugf("aborted status probe") } return false } diff --git a/remote/cloudmocks/files.go b/remote/cloudmocks/files.go index 1fbf25e..8bf2c26 100644 --- a/remote/cloudmocks/files.go +++ b/remote/cloudmocks/files.go @@ -2,14 +2,13 @@ package cloudmocks import ( "fmt" - "github.com/sirupsen/logrus" "os" "path/filepath" "strings" ) func (m Remote) syncFiles(dir string) error { - logrus.Debugf("synchronising files from: %s", dir) + logger.Debugf("synchronising files from: %s", dir) r, err := m.listRemote() if err != nil { @@ -36,7 +35,7 @@ func (m Remote) syncFiles(dir string) error { } func (m Remote) listLocal(dir string) ([]string, error) { - logrus.Tracef("listing files in: %s", dir) + logger.Tracef("listing files in: %s", dir) var files []string filenames, err := os.ReadDir(dir) @@ -71,7 +70,7 @@ func (m Remote) calculateDelta(dir string, remote []string, local []string) []st delta = append(delta, r) } } - logrus.Debugf("found %v remote files not present in local", len(delta)) + logger.Debugf("found %v remote files not present in local", len(delta)) return delta } @@ -89,7 +88,7 @@ func arrayContains(search []string, trimPrefix string, term string) bool { func (m Remote) uploadFiles(files []string) error { for _, f := range files { - logrus.Infof("uploading: %s", f) + logger.Infof("uploading: %s", f) err := m.upload("POST", fmt.Sprintf("/api/mocks/%s/spec", m.config.MockId), f) if err != nil { return fmt.Errorf("failed to upload file: %s: %s", f, err) @@ -100,7 +99,7 @@ func (m Remote) uploadFiles(files []string) error { func (m Remote) deleteRemote(files []string) error { for _, f := range files { - logrus.Infof("deleting remote file: %s", f) + logger.Infof("deleting remote file: %s", f) var resp interface{} err := m.request("DELETE", fmt.Sprintf("/api/mocks/%s/files/%s", m.config.MockId, f), &resp) if err != nil { diff --git a/remote/remote.go b/remote/remote.go index 57e948a..fb1afdc 100644 --- a/remote/remote.go +++ b/remote/remote.go @@ -2,8 +2,8 @@ package remote import ( "fmt" + "gatehill.io/imposter/logging" "gatehill.io/imposter/workspace" - "github.com/sirupsen/logrus" "os" "path/filepath" ) @@ -29,6 +29,8 @@ type Status struct { LastModified int } +var logger = logging.GetLogger() + var providers = make(map[string]func(dir string, workspace *workspace.Workspace) (Remote, error)) func Register(remoteType string, fn func(dir string, workspace *workspace.Workspace) (Remote, error)) { @@ -50,7 +52,7 @@ func SaveActiveRemoteType(dir string, remoteType string) (*workspace.Workspace, if err != nil { return nil, err } - logrus.Tracef("set remote type: %s for active workspace: %s", remoteType, active.Name) + logger.Tracef("set remote type: %s for active workspace: %s", remoteType, active.Name) return active, nil } @@ -60,7 +62,7 @@ func Load(dir string, workspace *workspace.Workspace) (*Remote, error) { return nil, fmt.Errorf("unsupported remote type: %s", workspace.RemoteType) } remote, err := provider(dir, workspace) - logrus.Tracef("loaded remote [%s] for workspace: %s", remote.GetType(), workspace.Name) + logger.Tracef("loaded remote [%s] for workspace: %s", remote.GetType(), workspace.Name) return &remote, err } @@ -88,12 +90,12 @@ func GetConfigPath(dir string, w *workspace.Workspace) (exists bool, remoteFileP remoteFilePath = filepath.Join(metadataDir, remoteFileName) if _, err = os.Stat(remoteFilePath); err != nil { if os.IsNotExist(err) { - logrus.Tracef("no remote config file for workspace: %s", w.Name) + logger.Tracef("no remote config file for workspace: %s", w.Name) return false, remoteFilePath, nil } else { return false, "", fmt.Errorf("failed to stat remote config file: %s: %s", remoteFilePath, err) } } - logrus.Tracef("found remote config file for workspace: %s: %s", w.Name, remoteFilePath) + logger.Tracef("found remote config file for workspace: %s: %s", w.Name, remoteFilePath) return true, remoteFilePath, nil } diff --git a/workspace/manage.go b/workspace/manage.go index 7723b82..b2a4699 100644 --- a/workspace/manage.go +++ b/workspace/manage.go @@ -2,12 +2,14 @@ package workspace import ( "fmt" - "github.com/sirupsen/logrus" + "gatehill.io/imposter/logging" "regexp" ) const namePattern = "[a-zA-Z0-9_-]+" +var logger = logging.GetLogger() + func New(dir string, name string) (*Workspace, error) { if match, _ := regexp.MatchString("^"+namePattern+"$", name); !match { return nil, fmt.Errorf("workspace name does not match pattern: %s", namePattern) @@ -48,7 +50,7 @@ func Delete(dir string, name string) error { if err != nil { return fmt.Errorf("failed to delete workspace: %s", err) } - logrus.Tracef("deleted workspace: %s", name) + logger.Tracef("deleted workspace: %s", name) return nil } @@ -62,7 +64,7 @@ func SetActive(dir string, name string) (*Workspace, error) { return nil, fmt.Errorf("no such workspace: %s", name) } - logrus.Tracef("setting active workspace: %s", name) + logger.Tracef("setting active workspace: %s", name) m.Active = name err = SaveMetadata(dir, m) if err != nil { @@ -82,14 +84,14 @@ func GetActiveWithMetadata(dir string) (*Workspace, *Metadata, error) { return nil, nil, fmt.Errorf("failed to get active workspace: %s", err) } if m.Active == "" { - logrus.Tracef("there is no active workspace") + logger.Tracef("there is no active workspace") return nil, nil, nil } w := getWorkspace(m.Workspaces, m.Active) if w == nil { return nil, nil, fmt.Errorf("active workspace: %s does not exist", m.Active) } - logrus.Tracef("active workspace is: %s [%s]", w.Name, w.RemoteType) + logger.Tracef("active workspace is: %s [%s]", w.Name, w.RemoteType) return w, m, nil } @@ -120,7 +122,7 @@ func createWorkspace(dir string, name string, m *Metadata) (*Workspace, error) { if err != nil { return nil, err } - logrus.Tracef("created new workspace: %s", name) + logger.Tracef("created new workspace: %s", name) return w, nil } diff --git a/workspace/meta.go b/workspace/meta.go index 06bccf3..2012801 100644 --- a/workspace/meta.go +++ b/workspace/meta.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "gatehill.io/imposter/library" - "github.com/sirupsen/logrus" "os" "path/filepath" ) @@ -28,7 +27,7 @@ func createOrLoadMetadata(dir string) (m *Metadata, err error) { } if _, err := os.Stat(metaFilePath); err != nil { if os.IsNotExist(err) { - logrus.Trace("creating empty workspace metadata") + logger.Trace("creating empty workspace metadata") m = &Metadata{} } else { return nil, fmt.Errorf("failed to stat workspace file: %s: %s", metaFilePath, err)