Create log file in append mode (#5497)

This commit is contained in:
scier 2019-02-27 16:33:38 -08:00 committed by Daniel Nelson
parent bfc8758db6
commit 7787ea2dcc
2 changed files with 27 additions and 10 deletions

View File

@ -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

View File

@ -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