package logging import ( "bytes" "context" "encoding/json" "io" "os" "testing" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "gitea.libretechconsulting.com/rmcguire/go-app/pkg/config" ) func TestMustInitLogging(t *testing.T) { cfg := &config.AppConfig{ Logging: &config.LogConfig{ Level: "info", Format: "json", }, } ctx := cfg.AddToCtx(context.Background()) ctx = MustInitLogging(ctx) logger := zerolog.Ctx(ctx) assert.NotNil(t, logger) assert.Equal(t, zerolog.InfoLevel, logger.GetLevel()) } func TestConfigureLogger(t *testing.T) { type args struct { cfg *config.LogConfig } tests := []struct { name string args args level zerolog.Level wantJSON bool wantTime bool assertion func(t *testing.T, output string) }{ { name: "json logger", args: args{ cfg: &config.LogConfig{ Level: "debug", Format: "json", }, }, level: zerolog.DebugLevel, wantJSON: true, }, { name: "console logger", args: args{ cfg: &config.LogConfig{ Level: "warn", Format: "console", }, }, level: zerolog.WarnLevel, wantJSON: false, }, { name: "with time", args: args{ cfg: &config.LogConfig{ Level: "info", Format: "json", TimeFormat: "unix", }, }, level: zerolog.InfoLevel, wantJSON: true, wantTime: true, assertion: func(t *testing.T, output string) { var log map[string]interface{} err := json.Unmarshal([]byte(output), &log) assert.NoError(t, err) assert.Contains(t, log, "time") }, }, { name: "without time", args: args{ cfg: &config.LogConfig{ Level: "info", Format: "json", TimeFormat: "off", }, }, level: zerolog.InfoLevel, wantJSON: true, wantTime: false, assertion: func(t *testing.T, output string) { var log map[string]interface{} err := json.Unmarshal([]byte(output), &log) assert.NoError(t, err) assert.NotContains(t, log, "time") }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Capture output old := os.Stderr r, w, _ := os.Pipe() os.Stderr = w logger, err := configureLogger(tt.args.cfg) assert.NoError(t, err) assert.Equal(t, tt.level, logger.GetLevel()) logger.Info().Msg("test") w.Close() os.Stderr = old var buf bytes.Buffer io.Copy(&buf, r) output := buf.String() if tt.assertion != nil { tt.assertion(t, output) } }) } }