From 0b3af0e0702258b37aafbe040d0e5abe3cad694c Mon Sep 17 00:00:00 2001 From: Deepjyoti Mondal Date: Sun, 19 Apr 2020 14:44:54 +0530 Subject: [PATCH] Relates to #7447 This PR will allow consul to throw log error if provided log directory has permission issues for writing or is non existent. Signed-off-by: Deepjyoti Mondal djmdeveloper060796@gmail.com --- logging/logger.go | 4 +++ logging/logger_test.go | 63 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/logging/logger.go b/logging/logger.go index 05237f5696..5e6c485ec1 100644 --- a/logging/logger.go +++ b/logging/logger.go @@ -130,6 +130,10 @@ func Setup(config *Config, ui cli.Ui) (hclog.InterceptLogger, *GatedWriter, io.W MaxBytes: logRotateBytes, MaxFiles: config.LogRotateMaxFiles, } + if err := logFile.openNew(); err != nil { + ui.Error(fmt.Sprintf("Failed to setup logging: %v", err)) + return nil, nil, nil, false + } writers = append(writers, logFile) } diff --git a/logging/logger_test.go b/logging/logger_test.go index 8c6104b421..49ef9aae96 100644 --- a/logging/logger_test.go +++ b/logging/logger_test.go @@ -2,8 +2,10 @@ package logging import ( "encoding/json" + "os" "testing" + "github.com/hashicorp/consul/sdk/testutil" "github.com/mitchellh/cli" "github.com/stretchr/testify/require" ) @@ -149,3 +151,64 @@ func TestLogger_SetupLoggerWithJSON(t *testing.T) { require.Contains(jsonOutput, "@message") require.Equal(jsonOutput["@message"], "test warn msg") } + +func TestLogger_SetupLoggerWithValidLogPath(t *testing.T) { + t.Parallel() + require := require.New(t) + + tmpDir := testutil.TempDir(t, t.Name()) + defer os.RemoveAll(tmpDir) + + cfg := &Config{ + LogLevel: "INFO", + LogFilePath: tmpDir + "/", + } + ui := cli.NewMockUi() + + logger, gatedWriter, writer, ok := Setup(cfg, ui) + require.True(ok) + require.NotNil(logger) + require.NotNil(gatedWriter) + require.NotNil(writer) +} + +func TestLogger_SetupLoggerWithInValidLogPath(t *testing.T) { + t.Parallel() + require := require.New(t) + + cfg := &Config{ + LogLevel: "INFO", + LogFilePath: "nonexistentdir/", + } + ui := cli.NewMockUi() + + logger, gatedWriter, writer, ok := Setup(cfg, ui) + require.Contains(ui.ErrorWriter.String(), "no such file or directory") + require.False(ok) + require.Nil(logger) + require.Nil(gatedWriter) + require.Nil(writer) +} + +func TestLogger_SetupLoggerWithInValidLogPathPermission(t *testing.T) { + t.Parallel() + require := require.New(t) + + tmpDir := "/tmp/" + t.Name() + + os.Mkdir(tmpDir, 0000) + defer os.RemoveAll(tmpDir) + + cfg := &Config{ + LogLevel: "INFO", + LogFilePath: tmpDir + "/", + } + ui := cli.NewMockUi() + + logger, gatedWriter, writer, ok := Setup(cfg, ui) + require.Contains(ui.ErrorWriter.String(), "permission denied") + require.False(ok) + require.Nil(logger) + require.Nil(gatedWriter) + require.Nil(writer) +}