Skip to content

Commit

Permalink
Fix developLog
Browse files Browse the repository at this point in the history
  • Loading branch information
rekby committed Mar 14, 2020
1 parent ee04435 commit 62e0571
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 8 deletions.
14 changes: 6 additions & 8 deletions cmd/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@ import (
"go.uber.org/zap"
)

type logWriteSyncer lumberjack.Logger

func (w *logWriteSyncer) Write(p []byte) (n int, err error) {
return (*lumberjack.Logger)(w).Write(p)
type logWriteSyncer struct {
*lumberjack.Logger
}

func (w *logWriteSyncer) Sync() error {
return (*lumberjack.Logger)(w).Close()
func (w logWriteSyncer) Sync() error {
return w.Logger.Close()
}

func initLogger(config logConfig) *zap.Logger {
Expand All @@ -38,7 +36,7 @@ func initLogger(config logConfig) *zap.Logger {
lr.MaxSize = int(math.MaxInt32) // about 2 Petabytes. Really no reachable in this scenario.
}

writeSyncer := (*logWriteSyncer)(lr)
writeSyncer := logWriteSyncer{lr}
writers = append(writers, writeSyncer)
}

Expand Down Expand Up @@ -99,7 +97,7 @@ func getLogOptions(config logConfig) (res []zap.Option) {
zap.AddCaller(),
}
if config.DeveloperMode {
res = append(res, zap.AddStacktrace(zapcore.WarnLevel))
res = append(res, zap.AddStacktrace(zapcore.WarnLevel), zap.Development())
} else {
res = append(res, zap.AddStacktrace(zapcore.ErrorLevel))
}
Expand Down
45 changes: 45 additions & 0 deletions cmd/log_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package main

import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"

"github.com/maxatome/go-testdeep"
Expand Down Expand Up @@ -34,3 +38,44 @@ func TestParseLogLever(t *testing.T) {
td.CmpError(err)
td.CmpDeeply(res, zapcore.InfoLevel)
}

func TestInitLogger(t *testing.T) {
td := testdeep.NewT(t)

tmpDir, err := ioutil.TempDir("", "")
if err != nil {
td.Fatal(err)
}
defer os.RemoveAll(tmpDir)

// LogToFile, logLevel
logFile := filepath.Join(tmpDir, "log.txt")
config := logConfig{
EnableLogToFile: true,
File: logFile,
LogLevel: "warning",
}
logger := initLogger(config)
testError := "errorTest"
testInfo := "infoTest"
logger.Error(testError)
logger.Info(testInfo)
logger.Sync()

fileBytes, err := ioutil.ReadFile(logFile)
td.CmpNoError(err)
td.True(strings.Contains(string(fileBytes), testError))
td.False(strings.Contains(string(fileBytes), testInfo))

// DevelMode
config = logConfig{DeveloperMode: false, LogLevel: "info", EnableLogToStdErr: true}
logger = initLogger(config)
logger.DPanic(testError)

config = logConfig{DeveloperMode: true, LogLevel: "info"}
logger = initLogger(config)
td.CmpPanic(func() {
logger.DPanic(testError)
}, testError)

}

0 comments on commit 62e0571

Please sign in to comment.