From dd83e251c12dac19fe7352d04867df4cb756ee4e Mon Sep 17 00:00:00 2001 From: FishGoddess <1149062639@qq.com> Date: Thu, 14 Dec 2023 03:04:41 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B0=83=E6=95=B4=E4=BB=A3=E7=A0=81=E7=BB=93?= =?UTF-8?q?=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FUTURE.md | 3 +- _examples/file.go | 2 +- _examples/handler.go | 5 +- _examples/option.go | 2 +- _examples/performance_test.go | 10 +- config.go | 6 +- config_test.go | 4 +- buffer.go => core/handler/buffer.go | 2 +- buffer_test.go => core/handler/buffer_test.go | 2 +- handler.go => core/handler/handler.go | 32 +++--- .../handler/handler_test.go | 12 +- standard.go => core/handler/mix.go | 108 ++++++++++-------- standard_test.go => core/handler/mix_test.go | 25 +++- {rotate => core/rotate}/backup.go | 0 {rotate => core/rotate}/backup_test.go | 0 {rotate => core/rotate}/config.go | 0 {rotate => core/rotate}/config_test.go | 0 {rotate => core/rotate}/file.go | 0 {rotate => core/rotate}/file_test.go | 0 {rotate => core/rotate}/option.go | 0 {rotate => core/rotate}/option_test.go | 0 {writer => core/writer}/batch.go | 0 {writer => core/writer}/batch_test.go | 0 {writer => core/writer}/buffer.go | 0 {writer => core/writer}/buffer_test.go | 0 {writer => core/writer}/writer.go | 0 {writer => core/writer}/writer_test.go | 0 doc.go | 7 +- {pkg => extension}/config/config.go | 4 +- {pkg => extension}/config/config_test.go | 0 {pkg => extension}/config/parse.go | 0 {pkg => extension}/config/parse_test.go | 0 logger_test.go | 18 +-- option.go | 15 +-- option_test.go | 17 +-- 35 files changed, 156 insertions(+), 118 deletions(-) rename buffer.go => core/handler/buffer.go (98%) rename buffer_test.go => core/handler/buffer_test.go (98%) rename handler.go => core/handler/handler.go (57%) rename handler_test.go => core/handler/handler_test.go (84%) rename standard.go => core/handler/mix.go (70%) rename standard_test.go => core/handler/mix_test.go (71%) rename {rotate => core/rotate}/backup.go (100%) rename {rotate => core/rotate}/backup_test.go (100%) rename {rotate => core/rotate}/config.go (100%) rename {rotate => core/rotate}/config_test.go (100%) rename {rotate => core/rotate}/file.go (100%) rename {rotate => core/rotate}/file_test.go (100%) rename {rotate => core/rotate}/option.go (100%) rename {rotate => core/rotate}/option_test.go (100%) rename {writer => core/writer}/batch.go (100%) rename {writer => core/writer}/batch_test.go (100%) rename {writer => core/writer}/buffer.go (100%) rename {writer => core/writer}/buffer_test.go (100%) rename {writer => core/writer}/writer.go (100%) rename {writer => core/writer}/writer_test.go (100%) rename {pkg => extension}/config/config.go (98%) rename {pkg => extension}/config/config_test.go (100%) rename {pkg => extension}/config/parse.go (100%) rename {pkg => extension}/config/parse_test.go (100%) diff --git a/FUTURE.md b/FUTURE.md index 4695b47..566aa94 100644 --- a/FUTURE.md +++ b/FUTURE.md @@ -18,7 +18,8 @@ * [x] 完善示例代码 * [x] 增加属性解析器适配功能 * [x] 优化 handler 和 writer 设计 -* [ ] 增加一个可读性高的 handler 实现 +* [x] 增加一个可读性高的 handler 实现 +* [ ] MixHandler 转义处理 * [ ] 提高单元测试覆盖率到 70% * [ ] 进一步提高单元测试覆盖率到 80% diff --git a/_examples/file.go b/_examples/file.go index 9589a8f..1da1452 100644 --- a/_examples/file.go +++ b/_examples/file.go @@ -16,7 +16,7 @@ package main import ( "github.com/FishGoddess/logit" - "github.com/FishGoddess/logit/rotate" + "github.com/FishGoddess/logit/core/rotate" ) func main() { diff --git a/_examples/handler.go b/_examples/handler.go index c9f71c4..a034029 100644 --- a/_examples/handler.go +++ b/_examples/handler.go @@ -19,6 +19,7 @@ import ( "log/slog" "github.com/FishGoddess/logit" + "github.com/FishGoddess/logit/core/handler" ) func main() { @@ -31,12 +32,12 @@ func main() { logger = logit.NewLogger(logit.WithJsonHandler()) logger.Info("using json handler") - // Or you want to use customized handlers, try RegisterHandler. + // Or you want to use customized handlers, try Register. newHandler := func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { return slog.NewTextHandler(w, opts) } - if err := logit.RegisterHandler("demo", newHandler); err != nil { + if err := handler.Register("demo", newHandler); err != nil { panic(err) } diff --git a/_examples/option.go b/_examples/option.go index 6fcb50c..611ac50 100644 --- a/_examples/option.go +++ b/_examples/option.go @@ -34,7 +34,7 @@ func main() { // Change logger handler: logit.WithHandler("xxx") - logit.WithStandardHandler() + logit.WithMixHandler() logit.WithTextHandler() logit.WithJsonHandler() diff --git a/_examples/performance_test.go b/_examples/performance_test.go index dc46b2a..73cd409 100644 --- a/_examples/performance_test.go +++ b/_examples/performance_test.go @@ -59,7 +59,7 @@ BenchmarkLogrusFile-2 174944 6491 ns/op func BenchmarkLogitLogger(b *testing.B) { logger := logit.NewLogger( logit.WithInfoLevel(), - logit.WithStandardHandler(), + logit.WithMixHandler(), logit.WithWriter(io.Discard), ) @@ -107,7 +107,7 @@ func BenchmarkLogitLoggerJsonHandler(b *testing.B) { func BenchmarkLogitLoggerPrint(b *testing.B) { logger := logit.NewLogger( logit.WithInfoLevel(), - logit.WithStandardHandler(), + logit.WithMixHandler(), logit.WithWriter(io.Discard), ) @@ -226,7 +226,7 @@ func BenchmarkLogitFile(b *testing.B) { logger := logit.NewLogger( logit.WithInfoLevel(), - logit.WithStandardHandler(), + logit.WithMixHandler(), logit.WithFile(path), ) @@ -244,7 +244,7 @@ func BenchmarkLogitFileWithBuffer(b *testing.B) { logger := logit.NewLogger( logit.WithInfoLevel(), - logit.WithStandardHandler(), + logit.WithMixHandler(), logit.WithFile(path), logit.WithBuffer(65536), ) @@ -265,7 +265,7 @@ func BenchmarkLogitFileWithBatch(b *testing.B) { logger := logit.NewLogger( logit.WithInfoLevel(), - logit.WithStandardHandler(), + logit.WithMixHandler(), logit.WithFile(path), logit.WithBatch(64), ) diff --git a/config.go b/config.go index fc7df67..04c976c 100644 --- a/config.go +++ b/config.go @@ -19,6 +19,8 @@ import ( "log/slog" "os" "time" + + "github.com/FishGoddess/logit/core/handler" ) type nilSyncer struct{} @@ -55,7 +57,7 @@ func newDefaultConfig() *config { conf := &config{ level: slog.LevelDebug, - handler: handlerStandard, + handler: handler.Mix, newWriter: newWriter, wrapWriter: nil, replaceAttr: nil, @@ -102,7 +104,7 @@ func (c *config) newHandlerOptions() *slog.HandlerOptions { } func (c *config) newHandler() (slog.Handler, Syncer, io.Closer, error) { - newHandler, err := getHandlerFunc(c.handler) + newHandler, err := handler.Get(c.handler) if err != nil { return nil, nil, nil, err } diff --git a/config_test.go b/config_test.go index 67f46af..b4b35d8 100644 --- a/config_test.go +++ b/config_test.go @@ -20,6 +20,8 @@ import ( "log/slog" "os" "testing" + + "github.com/FishGoddess/logit/core/handler" ) type testConfigHandler struct { @@ -58,7 +60,7 @@ func TestConfigNewHandlerOptions(t *testing.T) { func TestConfigNewHandler(t *testing.T) { handlerName := t.Name() - RegisterHandler(handlerName, func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { + handler.Register(handlerName, func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { return &testConfigHandler{ w: w, opts: *opts, diff --git a/buffer.go b/core/handler/buffer.go similarity index 98% rename from buffer.go rename to core/handler/buffer.go index fbb952d..bdaa5ca 100644 --- a/buffer.go +++ b/core/handler/buffer.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package logit +package handler import ( "sync" diff --git a/buffer_test.go b/core/handler/buffer_test.go similarity index 98% rename from buffer_test.go rename to core/handler/buffer_test.go index cf29b1b..399765d 100644 --- a/buffer_test.go +++ b/core/handler/buffer_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package logit +package handler import ( "testing" diff --git a/handler.go b/core/handler/handler.go similarity index 57% rename from handler.go rename to core/handler/handler.go index 3a5a827..c2e12b1 100644 --- a/handler.go +++ b/core/handler/handler.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package logit +package handler import ( "fmt" @@ -22,20 +22,20 @@ import ( ) const ( - handlerStandard = "standard" - handlerText = "text" - handlerJson = "json" + Mix = "mix" + Text = "text" + Json = "json" ) var ( - newHandlers = map[string]HandlerFunc{ - handlerStandard: func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { - return NewStandardHandler(w, opts) + newHandlers = map[string]NewHandlerFunc{ + Mix: func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { + return NewMixHandler(w, opts) }, - handlerText: func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { + Text: func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { return slog.NewTextHandler(w, opts) }, - handlerJson: func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { + Json: func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { return slog.NewJSONHandler(w, opts) }, } @@ -45,11 +45,11 @@ var ( newHandlersLock sync.RWMutex ) -// HandlerFunc is a function for creating slog.Handler with w and opts. -type HandlerFunc func(w io.Writer, opts *slog.HandlerOptions) slog.Handler +// NewHandlerFunc is a function for creating slog.Handler with w and opts. +type NewHandlerFunc func(w io.Writer, opts *slog.HandlerOptions) slog.Handler -// getHandlerFunc gets new handler func with name and returns an error if failed. -func getHandlerFunc(name string) (HandlerFunc, error) { +// Get gets new handler func with name and returns an error if failed. +func Get(name string) (NewHandlerFunc, error) { newHandlersLock.RLock() defer newHandlersLock.RUnlock() @@ -57,11 +57,11 @@ func getHandlerFunc(name string) (HandlerFunc, error) { return newHandler, nil } - return nil, fmt.Errorf("logit: handler %s unknown", name) + return nil, fmt.Errorf("logit: handler %s not found", name) } -// RegisterHandler registers newHandler with name to logit. -func RegisterHandler(name string, newHandler HandlerFunc) error { +// Register registers newHandler with name. +func Register(name string, newHandler NewHandlerFunc) error { newHandlersLock.Lock() defer newHandlersLock.Unlock() diff --git a/handler_test.go b/core/handler/handler_test.go similarity index 84% rename from handler_test.go rename to core/handler/handler_test.go index bf965e2..3f64a91 100644 --- a/handler_test.go +++ b/core/handler/handler_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package logit +package handler import ( "fmt" @@ -30,7 +30,7 @@ func TestGetHandlerFunc(t *testing.T) { handler := t.Name() newHandlers[handler] = newHandler - got, err := getHandlerFunc(handler) + got, err := Get(handler) if err != nil { t.Fatal(err) } @@ -40,10 +40,10 @@ func TestGetHandlerFunc(t *testing.T) { } } -// go test -v -cover -count=1 -test.cpu=1 -run=^TestRegisterHandler$ -func TestRegisterHandler(t *testing.T) { +// go test -v -cover -count=1 -test.cpu=1 -run=^TestRegister$ +func TestRegister(t *testing.T) { for name := range newHandlers { - if err := RegisterHandler(name, nil); err == nil { + if err := Register(name, nil); err == nil { t.Fatal("register an existed handler func should be failed") } } @@ -51,7 +51,7 @@ func TestRegisterHandler(t *testing.T) { handler := t.Name() newHandler := func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { return nil } - if err := RegisterHandler(handler, newHandler); err != nil { + if err := Register(handler, newHandler); err != nil { t.Fatal(err) } diff --git a/standard.go b/core/handler/mix.go similarity index 70% rename from standard.go rename to core/handler/mix.go index 7f4131f..7bd277b 100644 --- a/standard.go +++ b/core/handler/mix.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package logit +package handler import ( "bytes" @@ -51,7 +51,7 @@ var ( emptyAttr = slog.Attr{} ) -type standardHandler struct { +type mixHandler struct { w io.Writer opts slog.HandlerOptions @@ -61,16 +61,16 @@ type standardHandler struct { lock *sync.Mutex } -// NewStandardHandler creates a standard handler with w and opts. +// NewMixHandler creates a mix handler with w and opts. // This handler is more readable and faster than slog's handlers. -func NewStandardHandler(w io.Writer, opts *slog.HandlerOptions) slog.Handler { +func NewMixHandler(w io.Writer, opts *slog.HandlerOptions) slog.Handler { if opts == nil { opts = &slog.HandlerOptions{ Level: slog.LevelInfo, } } - handler := &standardHandler{ + handler := &mixHandler{ w: w, opts: *opts, lock: &sync.Mutex{}, @@ -80,47 +80,35 @@ func NewStandardHandler(w io.Writer, opts *slog.HandlerOptions) slog.Handler { } // WithAttrs returns a new handler with attrs. -func (sh *standardHandler) WithAttrs(attrs []slog.Attr) slog.Handler { +func (mh *mixHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) <= 0 { - return sh + return mh } - handler := *sh - handler.attrsBytes = sh.appendGroupAttrs(handler.attrsBytes, sh.group, attrs) + handler := *mh + handler.attrsBytes = mh.appendGroupAttrs(handler.attrsBytes, mh.group, attrs) return &handler } // WithGroup returns a new handler with group. -func (sh *standardHandler) WithGroup(name string) slog.Handler { +func (mh *mixHandler) WithGroup(name string) slog.Handler { if name == "" { - return sh + return mh } - handler := *sh + handler := *mh handler.group = name return &handler } // Enabled reports whether the logger should ignore logs whose level is lower than passed level. -func (sh *standardHandler) Enabled(ctx context.Context, level slog.Level) bool { - return level >= sh.opts.Level.Level() +func (mh *mixHandler) Enabled(ctx context.Context, level slog.Level) bool { + return level >= mh.opts.Level.Level() } -func (sh *standardHandler) appendGroupAttrs(bs []byte, group string, attrs []slog.Attr) []byte { - for _, groupAttr := range attrs { - if group != "" { - groupAttr.Key = group + groupSeparator + groupAttr.Key - } - - bs = sh.appendAttr(bs, groupAttr) - } - - return bs -} - -func (sh *standardHandler) appendTimeAttr(bs []byte, key string, value time.Time) []byte { +func (mh *mixHandler) appendTimeAttr(bs []byte, key string, value time.Time) []byte { if key != "" { bs = append(bs, key...) bs = append(bs, keyValueSeparator) @@ -191,12 +179,26 @@ func (sh *standardHandler) appendTimeAttr(bs []byte, key string, value time.Time return bs } -func (sh *standardHandler) appendAnyAttr(bs []byte, key string, value any) []byte { +func (mh *mixHandler) appendAnyAttr(bs []byte, key string, value any) []byte { if key != "" { bs = append(bs, key...) bs = append(bs, keyValueSeparator) } + if err, ok := value.(error); ok { + bs = append(bs, err.Error()...) + bs = append(bs, attrSeparator...) + + return bs + } + + if stringer, ok := value.(fmt.Stringer); ok { + bs = append(bs, stringer.String()...) + bs = append(bs, attrSeparator...) + + return bs + } + marshaled, err := json.Marshal(value) if err == nil { bs = append(bs, marshaled...) @@ -213,7 +215,7 @@ func (sh *standardHandler) appendAnyAttr(bs []byte, key string, value any) []byt return bs } -func (sh *standardHandler) appendStringAttr(bs []byte, key string, value string) []byte { +func (mh *mixHandler) appendStringAttr(bs []byte, key string, value string) []byte { if key != "" { bs = append(bs, key...) bs = append(bs, keyValueSeparator) @@ -225,7 +227,19 @@ func (sh *standardHandler) appendStringAttr(bs []byte, key string, value string) return bs } -func (sh *standardHandler) appendAttr(bs []byte, attr slog.Attr) []byte { +func (mh *mixHandler) appendGroupAttrs(bs []byte, group string, attrs []slog.Attr) []byte { + for _, groupAttr := range attrs { + if group != "" { + groupAttr.Key = group + groupSeparator + groupAttr.Key + } + + bs = mh.appendAttr(bs, groupAttr) + } + + return bs +} + +func (mh *mixHandler) appendAttr(bs []byte, attr slog.Attr) []byte { // Resolve the Attr's value before doing anything else. attr.Value = attr.Value.Resolve() @@ -234,21 +248,21 @@ func (sh *standardHandler) appendAttr(bs []byte, attr slog.Attr) []byte { } switch attr.Value.Kind() { - case slog.KindGroup: - bs = sh.appendGroupAttrs(bs, attr.Key, attr.Value.Group()) case slog.KindTime: - bs = sh.appendTimeAttr(bs, attr.Key, attr.Value.Time()) + bs = mh.appendTimeAttr(bs, attr.Key, attr.Value.Time()) case slog.KindAny: - bs = sh.appendAnyAttr(bs, attr.Key, attr.Value.Any()) + bs = mh.appendAnyAttr(bs, attr.Key, attr.Value.Any()) + case slog.KindGroup: + bs = mh.appendGroupAttrs(bs, attr.Key, attr.Value.Group()) default: - bs = sh.appendStringAttr(bs, attr.Key, attr.Value.String()) + bs = mh.appendStringAttr(bs, attr.Key, attr.Value.String()) } return bs } -func (sh *standardHandler) appendSource(bs []byte, pc uintptr) []byte { - if pc == 0 { +func (mh *mixHandler) appendSource(bs []byte, pc uintptr) []byte { + if !mh.opts.AddSource || pc == 0 { return bs } @@ -266,7 +280,7 @@ func (sh *standardHandler) appendSource(bs []byte, pc uintptr) []byte { } // Handle handles one record and returns an error if failed. -func (sh *standardHandler) Handle(ctx context.Context, record slog.Record) error { +func (mh *mixHandler) Handle(ctx context.Context, record slog.Record) error { // Setup a buffer for handling record. bufferPtr := newBuffer() buffer := *bufferPtr @@ -277,15 +291,15 @@ func (sh *standardHandler) Handle(ctx context.Context, record slog.Record) error }() // Handling record. - buffer = sh.appendTimeAttr(buffer, "", record.Time) - buffer = sh.appendStringAttr(buffer, "", record.Level.String()) - buffer = sh.appendStringAttr(buffer, "", record.Message) - buffer = sh.appendSource(buffer, record.PC) + buffer = mh.appendTimeAttr(buffer, "", record.Time) + buffer = mh.appendStringAttr(buffer, "", record.Level.String()) + buffer = mh.appendStringAttr(buffer, "", record.Message) + buffer = mh.appendSource(buffer, record.PC) - buffer = append(buffer, sh.attrsBytes...) + buffer = append(buffer, mh.attrsBytes...) if record.NumAttrs() > 0 { record.Attrs(func(attr slog.Attr) bool { - buffer = sh.appendAttr(buffer, attr) + buffer = mh.appendAttr(buffer, attr) return true }) } @@ -294,9 +308,9 @@ func (sh *standardHandler) Handle(ctx context.Context, record slog.Record) error buffer = append(buffer, lineBreak) // Write handled record. - sh.lock.Lock() - defer sh.lock.Unlock() + mh.lock.Lock() + defer mh.lock.Unlock() - _, err := sh.w.Write(buffer) + _, err := mh.w.Write(buffer) return err } diff --git a/standard_test.go b/core/handler/mix_test.go similarity index 71% rename from standard_test.go rename to core/handler/mix_test.go index f34f7fc..fa1261a 100644 --- a/standard_test.go +++ b/core/handler/mix_test.go @@ -12,21 +12,34 @@ // See the License for the specific language governing permissions and // limitations under the License. -package logit +package handler import ( + "io" "log/slog" + "os" "testing" "time" ) -// go test -v -cover -count=1 -test.cpu=1 -run=^TestStandardHandler$ -func TestStandardHandler(t *testing.T) { - logger1 := NewLogger(WithHandler(handlerStandard)).WithGroup("group1").With("id", 123456) - logger1.Info("using console handler 1", slog.Group("log_group1", "k1", 666)) +type demo struct { + value string +} + +func (d *demo) String() string { + return d.value +} + +// go test -v -cover -count=1 -test.cpu=1 -run=^TestMixHandler$ +func TestMixHandler(t *testing.T) { + handler := NewMixHandler(os.Stdout, nil) + + logger1 := slog.New(handler).WithGroup("group1").With("id", 123456) + logger1.Info("using console handler 1", slog.Group("log_group1", "k1", 666), "err", io.EOF) logger2 := logger1.WithGroup("group2").With("name", "fishgoddess") logger2.Info("using console handler 2", slog.Group("log_group2", "k2", 888), "t", time.Date(1977, 10, 24, 25, 35, 17, 222000000, time.Local)) - logger1.Info("using console handler 1", slog.Group("log_group1", "k1", 666)) + demo := &demo{"xxx"} + logger1.Info("using console handler 1", slog.Group("log_group1", "k1", 666), "demo", demo) } diff --git a/rotate/backup.go b/core/rotate/backup.go similarity index 100% rename from rotate/backup.go rename to core/rotate/backup.go diff --git a/rotate/backup_test.go b/core/rotate/backup_test.go similarity index 100% rename from rotate/backup_test.go rename to core/rotate/backup_test.go diff --git a/rotate/config.go b/core/rotate/config.go similarity index 100% rename from rotate/config.go rename to core/rotate/config.go diff --git a/rotate/config_test.go b/core/rotate/config_test.go similarity index 100% rename from rotate/config_test.go rename to core/rotate/config_test.go diff --git a/rotate/file.go b/core/rotate/file.go similarity index 100% rename from rotate/file.go rename to core/rotate/file.go diff --git a/rotate/file_test.go b/core/rotate/file_test.go similarity index 100% rename from rotate/file_test.go rename to core/rotate/file_test.go diff --git a/rotate/option.go b/core/rotate/option.go similarity index 100% rename from rotate/option.go rename to core/rotate/option.go diff --git a/rotate/option_test.go b/core/rotate/option_test.go similarity index 100% rename from rotate/option_test.go rename to core/rotate/option_test.go diff --git a/writer/batch.go b/core/writer/batch.go similarity index 100% rename from writer/batch.go rename to core/writer/batch.go diff --git a/writer/batch_test.go b/core/writer/batch_test.go similarity index 100% rename from writer/batch_test.go rename to core/writer/batch_test.go diff --git a/writer/buffer.go b/core/writer/buffer.go similarity index 100% rename from writer/buffer.go rename to core/writer/buffer.go diff --git a/writer/buffer_test.go b/core/writer/buffer_test.go similarity index 100% rename from writer/buffer_test.go rename to core/writer/buffer_test.go diff --git a/writer/writer.go b/core/writer/writer.go similarity index 100% rename from writer/writer.go rename to core/writer/writer.go diff --git a/writer/writer_test.go b/core/writer/writer_test.go similarity index 100% rename from writer/writer_test.go rename to core/writer/writer_test.go diff --git a/doc.go b/doc.go index 94add0d..d56eb7b 100644 --- a/doc.go +++ b/doc.go @@ -116,12 +116,12 @@ Package logit provides an easy way to use foundation for your logging operations logger = logit.NewLogger(logit.WithJsonHandler()) logger.Info("using json handler") - // Or you want to use customized handlers, try RegisterHandler. + // Or you want to use customized handlers, try Register. newHandler := func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { return slog.NewTextHandler(w, opts) } - if err := logit.RegisterHandler("demo", newHandler); err != nil { + if err := handler.Register("demo", newHandler); err != nil { panic(err) } @@ -204,7 +204,8 @@ Package logit provides an easy way to use foundation for your logging operations logit.WithDebugLevel() // Change logger handler: - logit.WithHandler("standard") + logit.WithHandler("xxx") + logit.WithMixHandler() logit.WithTextHandler() logit.WithJsonHandler() diff --git a/pkg/config/config.go b/extension/config/config.go similarity index 98% rename from pkg/config/config.go rename to extension/config/config.go index 73863a2..27b4340 100644 --- a/pkg/config/config.go +++ b/extension/config/config.go @@ -19,7 +19,7 @@ import ( "strings" "github.com/FishGoddess/logit" - "github.com/FishGoddess/logit/rotate" + "github.com/FishGoddess/logit/core/rotate" ) type WriterConfig struct { @@ -161,7 +161,7 @@ type Config struct { Level string `json:"level" yaml:"level" toml:"level" bson:"level"` // Handler is how the handler handles the logs. - // Values: "standard", "text", "json". + // Values: "mix", "text", "json". // Also, you can register your handlers to logit, see RegisterHandler. Handler string `json:"handler" yaml:"handler" toml:"handler" bson:"handler"` diff --git a/pkg/config/config_test.go b/extension/config/config_test.go similarity index 100% rename from pkg/config/config_test.go rename to extension/config/config_test.go diff --git a/pkg/config/parse.go b/extension/config/parse.go similarity index 100% rename from pkg/config/parse.go rename to extension/config/parse.go diff --git a/pkg/config/parse_test.go b/extension/config/parse_test.go similarity index 100% rename from pkg/config/parse_test.go rename to extension/config/parse_test.go diff --git a/logger_test.go b/logger_test.go index 21bdbdb..d44fe76 100644 --- a/logger_test.go +++ b/logger_test.go @@ -20,6 +20,8 @@ import ( "log/slog" "strings" "testing" + + "github.com/FishGoddess/logit/core/handler" ) type testLoggerHandler struct { @@ -31,15 +33,15 @@ type testLoggerHandler struct { // go test -v -cover -count=1 -test.cpu=1 -run=^TestNewLogger$ func TestNewLogger(t *testing.T) { handlerName := t.Name() - handler := &testLoggerHandler{} + testHandler := &testLoggerHandler{} - RegisterHandler(handlerName, func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { - return handler + handler.Register(handlerName, func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { + return testHandler }) logger := NewLogger(WithHandler(handlerName)) - if logger.handler != handler { - t.Fatalf("logger.handler %+v != handler %+v", logger.handler, handler) + if logger.handler != testHandler { + t.Fatalf("logger.handler %+v != testHandler %+v", logger.handler, testHandler) } } @@ -183,17 +185,17 @@ func removeTimeAndSource(str string) string { // go test -v -cover -count=1 -test.cpu=1 -run=^TestLogger$ func TestLogger(t *testing.T) { - handler := t.Name() + handlerName := t.Name() newHandler := func(w io.Writer, opts *slog.HandlerOptions) slog.Handler { return slog.NewTextHandler(w, opts) } - RegisterHandler(handler, newHandler) + handler.Register(handlerName, newHandler) buffer := bytes.NewBuffer(make([]byte, 0, 1024)) logger := NewLogger( - WithDebugLevel(), WithHandler(handler), WithWriter(buffer), WithSource(), WithPID(), + WithDebugLevel(), WithHandler(handlerName), WithWriter(buffer), WithSource(), WithPID(), ) logger.Debug("debug msg", "key1", 1) diff --git a/option.go b/option.go index 4b02e75..f128ee5 100644 --- a/option.go +++ b/option.go @@ -21,9 +21,10 @@ import ( "path/filepath" "time" + "github.com/FishGoddess/logit/core/handler" + "github.com/FishGoddess/logit/core/rotate" + "github.com/FishGoddess/logit/core/writer" "github.com/FishGoddess/logit/defaults" - "github.com/FishGoddess/logit/rotate" - "github.com/FishGoddess/logit/writer" ) // Option sets some fields to config. @@ -168,24 +169,24 @@ func WithHandler(handler string) Option { } } -// WithStandardHandler sets standard handler to config. -func WithStandardHandler() Option { +// WithMixHandler sets mix handler to config. +func WithMixHandler() Option { return func(conf *config) { - conf.handler = handlerStandard + conf.handler = handler.Mix } } // WithTextHandler sets text handler to config. func WithTextHandler() Option { return func(conf *config) { - conf.handler = handlerText + conf.handler = handler.Text } } // WithJsonHandler sets json handler to config. func WithJsonHandler() Option { return func(conf *config) { - conf.handler = handlerJson + conf.handler = handler.Json } } diff --git a/option_test.go b/option_test.go index 82ccdf3..69d8322 100644 --- a/option_test.go +++ b/option_test.go @@ -23,8 +23,9 @@ import ( "testing" "time" - "github.com/FishGoddess/logit/rotate" - "github.com/FishGoddess/logit/writer" + "github.com/FishGoddess/logit/core/handler" + "github.com/FishGoddess/logit/core/rotate" + "github.com/FishGoddess/logit/core/writer" ) // go test -v -cover -count=1 -test.cpu=1 -run=^TestWithDebugLevel$ @@ -294,12 +295,12 @@ func TestWithHandler(t *testing.T) { } } -// go test -v -cover -count=1 -test.cpu=1 -run=^TestWithStandardHandler$ -func TestWithStandardHandler(t *testing.T) { +// go test -v -cover -count=1 -test.cpu=1 -run=^TestWithMixHandler$ +func TestWithMixHandler(t *testing.T) { conf := &config{handler: ""} - WithStandardHandler().applyTo(conf) + WithMixHandler().applyTo(conf) - if conf.handler != handlerStandard { + if conf.handler != handler.Mix { t.Fatal("conf.handler is wrong") } } @@ -309,7 +310,7 @@ func TestWithTextHandler(t *testing.T) { conf := &config{handler: ""} WithTextHandler().applyTo(conf) - if conf.handler != handlerText { + if conf.handler != handler.Text { t.Fatal("conf.handler is wrong") } } @@ -319,7 +320,7 @@ func TestWithJsonHandler(t *testing.T) { conf := &config{handler: ""} WithJsonHandler().applyTo(conf) - if conf.handler != handlerJson { + if conf.handler != handler.Json { t.Fatal("conf.handler is wrong") } }