From 7787ea2dcc55f37f1baffe1a89266aa93a7cf14c Mon Sep 17 00:00:00 2001 From: scier Date: Wed, 27 Feb 2019 16:33:38 -0800 Subject: [PATCH] Create log file in append mode (#5497) --- logger/logger.go | 14 ++++---------- logger/logger_test.go | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/logger/logger.go b/logger/logger.go index 7ad1c8069..6250dedd6 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -50,16 +50,10 @@ func SetupLogging(debug, quiet bool, logfile string) { var oFile *os.File if logfile != "" { - if _, err := os.Stat(logfile); os.IsNotExist(err) { - if oFile, err = os.Create(logfile); err != nil { - log.Printf("E! Unable to create %s (%s), using stderr", logfile, err) - oFile = os.Stderr - } - } else { - if oFile, err = os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil { - log.Printf("E! Unable to append to %s (%s), using stderr", logfile, err) - oFile = os.Stderr - } + var err error + if oFile, err = os.OpenFile(logfile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeAppend|0644); err != nil { + log.Printf("E! Unable to open %s (%s), using stderr", logfile, err) + oFile = os.Stderr } } else { oFile = os.Stderr diff --git a/logger/logger_test.go b/logger/logger_test.go index 09c7c82eb..a721cbba7 100644 --- a/logger/logger_test.go +++ b/logger/logger_test.go @@ -64,6 +64,29 @@ func TestAddDefaultLogLevel(t *testing.T) { assert.Equal(t, f[19:], []byte("Z I! TEST\n")) } +func TestWriteToTruncatedFile(t *testing.T) { + tmpfile, err := ioutil.TempFile("", "") + assert.NoError(t, err) + defer func() { os.Remove(tmpfile.Name()) }() + + SetupLogging(true, false, tmpfile.Name()) + log.Printf("TEST") + + f, err := ioutil.ReadFile(tmpfile.Name()) + assert.NoError(t, err) + assert.Equal(t, f[19:], []byte("Z I! TEST\n")) + + tmpf, err := os.OpenFile(tmpfile.Name(), os.O_TRUNC, 0644) + assert.NoError(t, err) + assert.NoError(t, tmpf.Close()) + + log.Printf("SHOULD BE FIRST") + + f, err = ioutil.ReadFile(tmpfile.Name()) + assert.NoError(t, err) + assert.Equal(t, f[19:], []byte("Z I! SHOULD BE FIRST\n")) +} + func BenchmarkTelegrafLogWrite(b *testing.B) { var msg = []byte("test") var buf bytes.Buffer