Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion log/logger/daily.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ func (daily *Daily) Handle(channel string) (logrus.Hook, error) {
logPath+"-%Y-%m-%d"+ext,
rotatelogs.WithRotationTime(time.Duration(24)*time.Hour),
rotatelogs.WithRotationCount(uint(daily.config.GetInt(channel+".days"))),
rotatelogs.WithClock(rotatelogs.NewClock(carbon.Now().StdTime())),
// When using carbon.SetTestNow(), carbon.Now().StdTime() should always be used to get the current time.
// Hence, WithLocation cannot be used here.
rotatelogs.WithClock(NewRotatelogsClock()),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about using rotatelogs.WithLocation(carbon.Now().StdTime().Location()) instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As the annotation said, rotatelogs.WithLocation cannot cover the carbon.SetTestNow() case.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main reason is carbon.SetTestNow(), the time may be fake. The location is fixed when using rotatelogs.WithLocation(carbon.Now().StdTime().Location()).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My bad, I forgot carbon.SetTestNow.

)
if err != nil {
return hook, err
Expand All @@ -61,3 +63,13 @@ func (daily *Daily) Handle(channel string) (logrus.Hook, error) {
formatter.NewGeneral(daily.config, daily.json),
), nil
}

type rotatelogsClock struct{}

func (clock *rotatelogsClock) Now() time.Time {
return carbon.Now().StdTime()
}

func NewRotatelogsClock() rotatelogs.Clock {
return &rotatelogsClock{}
}
25 changes: 13 additions & 12 deletions log/logrus_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"maps"
"os"

"github.com/dromara/carbon/v2"
"github.com/rotisserie/eris"
"github.com/sirupsen/logrus"

Expand Down Expand Up @@ -61,57 +62,57 @@ func NewWriter(instance *logrus.Entry) log.Writer {
}

func (r *Writer) Debug(args ...any) {
r.instance.WithField("root", r.toMap()).Debug(args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Debug(args...)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The time is incorrect when using carbon.SetTestNow(), so it should be reset here.

}

func (r *Writer) Debugf(format string, args ...any) {
r.instance.WithField("root", r.toMap()).Debugf(format, args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Debugf(format, args...)
}

func (r *Writer) Info(args ...any) {
r.instance.WithField("root", r.toMap()).Info(args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Info(args...)
}

func (r *Writer) Infof(format string, args ...any) {
r.instance.WithField("root", r.toMap()).Infof(format, args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Infof(format, args...)
}

func (r *Writer) Warning(args ...any) {
r.instance.WithField("root", r.toMap()).Warning(args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Warning(args...)
}

func (r *Writer) Warningf(format string, args ...any) {
r.instance.WithField("root", r.toMap()).Warningf(format, args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Warningf(format, args...)
}

func (r *Writer) Error(args ...any) {
r.withStackTrace(fmt.Sprint(args...))
r.instance.WithField("root", r.toMap()).Error(args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Error(args...)
}

func (r *Writer) Errorf(format string, args ...any) {
r.withStackTrace(fmt.Sprintf(format, args...))
r.instance.WithField("root", r.toMap()).Errorf(format, args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Errorf(format, args...)
}

func (r *Writer) Fatal(args ...any) {
r.withStackTrace(fmt.Sprint(args...))
r.instance.WithField("root", r.toMap()).Fatal(args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Fatal(args...)
}

func (r *Writer) Fatalf(format string, args ...any) {
r.withStackTrace(fmt.Sprintf(format, args...))
r.instance.WithField("root", r.toMap()).Fatalf(format, args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Fatalf(format, args...)
}

func (r *Writer) Panic(args ...any) {
r.withStackTrace(fmt.Sprint(args...))
r.instance.WithField("root", r.toMap()).Panic(args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Panic(args...)
}

func (r *Writer) Panicf(format string, args ...any) {
r.withStackTrace(fmt.Sprintf(format, args...))
r.instance.WithField("root", r.toMap()).Panicf(format, args...)
r.instance.WithTime(carbon.Now().StdTime()).WithField("root", r.toMap()).Panicf(format, args...)
}

// Code set a code or slug that describes the error.
Expand Down
56 changes: 44 additions & 12 deletions log/logrus_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import (
"github.com/stretchr/testify/assert"

contractshttp "github.com/goravel/framework/contracts/http"
logcontracts "github.com/goravel/framework/contracts/log"
contractslog "github.com/goravel/framework/contracts/log"
"github.com/goravel/framework/foundation/json"
configmock "github.com/goravel/framework/mocks/config"
mocksconfig "github.com/goravel/framework/mocks/config"
"github.com/goravel/framework/support/carbon"
"github.com/goravel/framework/support/file"
)
Expand All @@ -28,7 +28,7 @@ var (

func TestLogrus(t *testing.T) {
var (
mockConfig *configmock.Config
mockConfig *mocksconfig.Config
log *Application
j = json.New()
err error
Expand Down Expand Up @@ -387,11 +387,43 @@ func TestLogrus(t *testing.T) {
test.assert()
})
}

_ = file.Remove("storage")
}

func TestLogrus_DailyLogWithDifferentDays(t *testing.T) {
mockConfig := initMockConfig()
mockDriverConfig(mockConfig)

log, err := NewApplication(mockConfig, json.New())
assert.Nil(t, err)
assert.NotNil(t, log)

log.Info("Goravel")

date := carbon.Now().Format("Y-m-d H:i")
assert.True(t, file.Contain(singleLog, date))
assert.True(t, file.Contain(singleLog, "test.info: Goravel"))
assert.True(t, file.Contain(dailyLog, date))
assert.True(t, file.Contain(dailyLog, "test.info: Goravel"))

nextDailyLog := fmt.Sprintf("storage/logs/goravel-%s.log", carbon.Now().AddDay().ToDateString())
carbon.SetTestNow(carbon.Now().AddDay())
defer carbon.ClearTestNow()

log.Info("Goravel Next Day")

date = carbon.Now().Format("Y-m-d H:i")
assert.True(t, file.Contain(singleLog, date))
assert.True(t, file.Contain(singleLog, "test.info: Goravel Next Day"))
assert.True(t, file.Contain(nextDailyLog, date))
assert.True(t, file.Contain(nextDailyLog, "test.info: Goravel Next Day"))

_ = file.Remove("storage")
}

func TestLogrusWithCustomLogger(t *testing.T) {
mockConfig := configmock.NewConfig(t)
mockConfig := mocksconfig.NewConfig(t)
mockConfig.EXPECT().GetString("logging.default").Return("customLogger").Once()
mockConfig.EXPECT().GetString("logging.channels.customLogger.driver").Return("custom").Twice()
mockConfig.EXPECT().Get("logging.channels.customLogger.via").Return(&CustomLogger{}).Twice()
Expand Down Expand Up @@ -541,8 +573,8 @@ func Benchmark_Panic(b *testing.B) {
_ = file.Remove("storage")
}

func initMockConfig() *configmock.Config {
mockConfig := &configmock.Config{}
func initMockConfig() *mocksconfig.Config {
mockConfig := &mocksconfig.Config{}
mockConfig.EXPECT().GetString("logging.default").Return("stack").Once()
mockConfig.EXPECT().GetString("logging.channels.stack.driver").Return("stack").Once()
mockConfig.On("Get", "logging.channels.stack.channels").Return([]string{"single", "daily"}).Once()
Expand All @@ -557,7 +589,7 @@ func initMockConfig() *configmock.Config {
return mockConfig
}

func mockDriverConfig(mockConfig *configmock.Config) {
func mockDriverConfig(mockConfig *mocksconfig.Config) {
mockConfig.EXPECT().GetString("logging.channels.daily.level").Return("debug").Once()
mockConfig.EXPECT().GetString("logging.channels.single.level").Return("debug").Once()
mockConfig.EXPECT().GetString("app.env").Return("test")
Expand All @@ -566,20 +598,20 @@ func mockDriverConfig(mockConfig *configmock.Config) {
type CustomLogger struct {
}

func (logger *CustomLogger) Handle(channel string) (logcontracts.Hook, error) {
func (logger *CustomLogger) Handle(channel string) (contractslog.Hook, error) {
return &CustomHook{}, nil
}

type CustomHook struct {
}

func (h *CustomHook) Levels() []logcontracts.Level {
return []logcontracts.Level{
logcontracts.InfoLevel,
func (h *CustomHook) Levels() []contractslog.Level {
return []contractslog.Level{
contractslog.InfoLevel,
}
}

func (h *CustomHook) Fire(entry logcontracts.Entry) error {
func (h *CustomHook) Fire(entry contractslog.Entry) error {
with := entry.With()
filename, ok := with["filename"]
if ok {
Expand Down