Skip to content

Commit

Permalink
调整初始化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
FishGoddess committed Nov 26, 2023
1 parent 1d86bf4 commit 78d92a1
Show file tree
Hide file tree
Showing 37 changed files with 397 additions and 378 deletions.
25 changes: 25 additions & 0 deletions _examples/basic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright 2023 FishGoddess. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import "github.com/FishGoddess/logit"

func main() {
logger := logit.Builder().MustBuild()
defer logger.Close()

logger.Debug("new version of logit", "version", "1.5.0-alpha", "date", 20231122)
logger.Error("new version of logit", "version", "1.5.0-alpha", "date", 20231122)
}
225 changes: 225 additions & 0 deletions builder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
// Copyright 2023 FishGoddess. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package logit

import (
"io"
"log/slog"
"os"
"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"
)

var (
_ NewHandlerFunc = handler.NewTextHandler
_ NewHandlerFunc = handler.NewJsonHandler
)

type NewHandlerFunc func(w io.Writer, opts *slog.HandlerOptions) slog.Handler

type ReplaceAttrFunc func(groups []string, attr slog.Attr) slog.Attr

type LoggerBuilder struct {
level Level

newWriter func() (io.Writer, error)
wrapWriter func(io.Writer) writer.Writer

newHandler NewHandlerFunc
replaceAttr ReplaceAttrFunc

withSource bool
withPID bool
}

func Builder() *LoggerBuilder {
newWriter := func() (io.Writer, error) {
return os.Stdout, nil
}

builder := &LoggerBuilder{
level: levelDebug,
newWriter: newWriter,
wrapWriter: writer.Wrap,
newHandler: handler.NewTextHandler,
replaceAttr: nil,
withSource: false,
withPID: false,
}

return builder
}

func (lb *LoggerBuilder) SetLevel(level Level) *LoggerBuilder {
lb.level = level
return lb
}

func (lb *LoggerBuilder) WriteTo(w io.Writer) *LoggerBuilder {
newWriter := func() (io.Writer, error) {
return w, nil
}

lb.newWriter = newWriter
return lb
}

func (lb *LoggerBuilder) WriteToStdout() *LoggerBuilder {
newWriter := func() (io.Writer, error) {
return os.Stdout, nil
}

lb.newWriter = newWriter
return lb
}

func (lb *LoggerBuilder) WriteToStderr() *LoggerBuilder {
newWriter := func() (io.Writer, error) {
return os.Stderr, nil
}

lb.newWriter = newWriter
return lb
}

func (lb *LoggerBuilder) WriteToFile(path string) *LoggerBuilder {
newWriter := func() (io.Writer, error) {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, defaults.FileDirMode); err != nil {
return nil, err
}

return defaults.OpenFile(path, defaults.FileMode)
}

lb.newWriter = newWriter
return lb
}

func (lb *LoggerBuilder) WriteToRotateFile(path string, opts ...rotate.Option) *LoggerBuilder {
newWriter := func() (io.Writer, error) {
return rotate.New(path, opts...)
}

lb.newWriter = newWriter
return lb
}

func (lb *LoggerBuilder) runWriterSyncTask(w writer.Writer, frequency time.Duration) {
if frequency <= 0 {
return
}

go func() {
for {
time.Sleep(frequency)

if err := w.Sync(); err != nil {
defaults.HandleError("writer.sync", err)
}
}
}()
}

func (lb *LoggerBuilder) UseBuffer(bufferSize uint64, syncFrequency time.Duration) *LoggerBuilder {
wrapWriter := func(w io.Writer) writer.Writer {
ww := writer.Buffer(w, bufferSize)

lb.runWriterSyncTask(ww, syncFrequency)
return ww
}

lb.wrapWriter = wrapWriter
return lb
}

func (lb *LoggerBuilder) UseBatch(batchSize uint64, syncFrequency time.Duration) *LoggerBuilder {
wrapWriter := func(w io.Writer) writer.Writer {
ww := writer.Batch(w, batchSize)

lb.runWriterSyncTask(ww, syncFrequency)
return ww
}

lb.wrapWriter = wrapWriter
return lb
}

func (lb *LoggerBuilder) UseHandler(newHandler NewHandlerFunc) *LoggerBuilder {
lb.newHandler = newHandler
return lb
}

func (lb *LoggerBuilder) UseTextHandler() *LoggerBuilder {
lb.newHandler = handler.NewTextHandler
return lb
}

func (lb *LoggerBuilder) UseJsonHandler() *LoggerBuilder {
lb.newHandler = handler.NewJsonHandler
return lb
}

func (lb *LoggerBuilder) WithSource() *LoggerBuilder {
lb.withSource = true
return lb
}

func (lb *LoggerBuilder) WithPID() *LoggerBuilder {
lb.withPID = true
return lb
}

func (lb *LoggerBuilder) newHandlerOptions() *slog.HandlerOptions {
opts := &slog.HandlerOptions{
Level: lb.level,
AddSource: lb.withSource,
ReplaceAttr: lb.replaceAttr,
}

return opts
}

func (lb *LoggerBuilder) Build() (*Logger, error) {
w, err := lb.newWriter()
if err != nil {
return nil, err
}

ww := lb.wrapWriter(w)
opts := lb.newHandlerOptions()

logger := &Logger{
handler: lb.newHandler(ww, opts),
withSource: lb.withSource,
withPID: lb.withPID,
}

return logger, nil
}

func (lb *LoggerBuilder) MustBuild() *Logger {
logger, err := lb.Build()
if err != nil {
panic(err)
}

return logger
}
File renamed without changes.
49 changes: 14 additions & 35 deletions config.go → config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package logit
package config

import (
"fmt"
Expand All @@ -24,10 +24,9 @@ import (
"strings"
"time"

"github.com/FishGoddess/logit/core/rotate"
"github.com/FishGoddess/logit/core/writer"
"github.com/FishGoddess/logit/defaults"
"github.com/FishGoddess/logit/io/file"
"github.com/FishGoddess/logit/io/size"
"github.com/FishGoddess/logit/io/writer"
)

type WriterConfig struct {
Expand All @@ -51,7 +50,7 @@ type WriterConfig struct {

// BatchSize is the size of a batch.
// Only available when mode is "batch".
BatchSize uint `json:"batch_size" yaml:"batch_size" toml:"batch_size" bson:"batch_size"`
BatchSize uint64 `json:"batch_size" yaml:"batch_size" toml:"batch_size" bson:"batch_size"`

// AutoSync is the frequency of syncing.
// An empty string means syncing is manual.
Expand Down Expand Up @@ -172,19 +171,19 @@ func (c *Config) parseTimeDuration(s string) (time.Duration, error) {

func (c *Config) newFile() (io.Writer, error) {
if c.File.Rotate {
opts := []file.Option{
file.WithMode(c.File.Mode),
file.WithDirMode(c.File.DirMode),
file.WithTimeFormat("20060102150405"),
opts := []rotate.Option{
rotate.WithMode(c.File.Mode),
rotate.WithDirMode(c.File.DirMode),
rotate.WithTimeFormat("20060102150405"),
}

if c.File.MaxSize != "" {
maxSize, err := size.ParseByteSize(c.File.MaxSize)
maxSize, err := parseByteSize(c.File.MaxSize)
if err != nil {
return nil, err
}

opts = append(opts, file.WithMaxSize(maxSize))
opts = append(opts, rotate.WithMaxSize(maxSize))
}

if c.File.MaxAge != "" {
Expand All @@ -193,14 +192,14 @@ func (c *Config) newFile() (io.Writer, error) {
return nil, err
}

opts = append(opts, file.WithMaxAge(maxAge))
opts = append(opts, rotate.WithMaxAge(maxAge))
}

if c.File.MaxBackups > 0 {
opts = append(opts, file.WithMaxBackups(c.File.MaxBackups))
opts = append(opts, rotate.WithMaxBackups(c.File.MaxBackups))
}

return file.New(c.File.Path)
return rotate.New(c.File.Path, opts...)
}

dir := filepath.Dir(c.File.Path)
Expand Down Expand Up @@ -234,7 +233,7 @@ func (c *Config) newWriter() (io.Writer, error) {
case "direct":
break
case "buffer":
bufferSize, err := size.ParseByteSize(c.Writer.BufferSize)
bufferSize, err := parseByteSize(c.Writer.BufferSize)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -265,23 +264,3 @@ func (c *Config) newWriter() (io.Writer, error) {

return w, nil
}

func (c *Config) newHandlerOptions() *slog.HandlerOptions {
opts := &slog.HandlerOptions{
Level: parseLevel(c.Level),
AddSource: c.WithSource,
ReplaceAttr: c.replaceAttr,
}

return opts
}

func (c *Config) NewHandler() (slog.Handler, error) {
w, err := c.newWriter()
if err != nil {
return nil, err
}

opts := c.newHandlerOptions()
return newHandler(c.Handler, w, opts)
}
2 changes: 1 addition & 1 deletion handler/handler_test.go → config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package handler
package config
Loading

0 comments on commit 78d92a1

Please sign in to comment.