Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add CronLogAdapter #88 #96

Merged
merged 13 commits into from
Mar 17, 2021
21 changes: 21 additions & 0 deletions cronopts/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package cronopts

import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
)

// CronLogAdapter is an adapter between kitlog and cron logger interface
type CronLogAdapter struct {
Logging log.Logger
}

// Info implements cron.Logger
func (r CronLogAdapter) Info(msg string, keysAndValues ...interface{}) {
Copy link
Member

Choose a reason for hiding this comment

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

一般接收器变量的命名是接收器类型的第一个小写字母。

_ = level.Info(r.Logging).Log(append([]interface{}{"msg", msg}, keysAndValues...)...)
}

// Error implements cron.Logger
func (r CronLogAdapter) Error(err error, msg string, keysAndValues ...interface{}) {
_ = level.Error(r.Logging).Log(append([]interface{}{"msg", msg, "err", err}, keysAndValues...)...)
}
23 changes: 23 additions & 0 deletions cronopts/log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package cronopts

import (
"bytes"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"testing"
)

func TestCronLogAdapter_Info(t *testing.T) {
var buf bytes.Buffer
l := CronLogAdapter{Logging: log.NewLogfmtLogger(&buf)}
l.Info("msg", "key","value")
assert.Equal(t, "level=info msg=msg key=value\n", buf.String())
}

func TestCronLogAdapter_Error(t *testing.T) {
var buf bytes.Buffer
l := CronLogAdapter{Logging: log.NewLogfmtLogger(&buf)}
l.Error(errors.New("err"),"msg", "key","value")
assert.Equal(t, "level=error msg=msg err=err key=value\n",buf.String())
}
4 changes: 3 additions & 1 deletion serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package core
import (
"context"
"github.com/DoNewsCode/core/events"
"github.com/DoNewsCode/core/cronopts"
"net"
"net/http"
"os"
Expand Down Expand Up @@ -123,8 +124,9 @@ func newServeCmd(p serveIn) *cobra.Command {
// Start cron runner
if !p.Config.Bool("cron.disable") {
if p.Cron == nil {
p.Cron = cron.New()
p.Cron = cron.New(cron.WithLogger(cronopts.CronLogAdapter{Logging: l}))
}

p.Container.ApplyCron(p.Cron)
g.Add(func() error {
l.Info("cron runner started")
Expand Down