Skip to content

Commit

Permalink
update: update some handler create logic
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Apr 23, 2022
1 parent e1bfeed commit e206a26
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 101 deletions.
21 changes: 11 additions & 10 deletions benchmark2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,8 @@ func TestLogger_newRecord_AllocTimes(t *testing.T) {
}

func Test_formatArgsWithSpaces_oneElem_AllocTimes(t *testing.T) {
l := Std()
l.Output = ioutil.Discard
defer l.Reset()

// output: 1 times -> 0 times
fmt.Println("Alloc Times:", int(testing.AllocsPerRun(100, func() {
fmt.Println("Alloc Times:", int(testing.AllocsPerRun(10, func() {
// logger.Info("rate", "15", "low", 16, "high", 123.2, msg)
formatArgsWithSpaces([]interface{}{
"msg", // 2343, -23, 123.2,
Expand Down Expand Up @@ -67,7 +63,8 @@ func TestRecord_logBytes_AllocTimes(t *testing.T) {
r := l.newRecord()

_, _ = bb.Write([]byte("info message"))
r.logBytes(InfoLevel, bb.B)
r.Message = string(bb.B)
r.logBytes(InfoLevel)

l.releaseRecord(r)
})))
Expand Down Expand Up @@ -105,16 +102,20 @@ func Test_AllocTimes_stringsPool(t *testing.T) {

func TestLogger_Info_AllocTimes(t *testing.T) {
l := Std()
l.Output = ioutil.Discard
// l.Output = ioutil.Discard
l.ReportCaller = false
l.LowerLevelName = true
// 启用 color 会导致多次(10次左右)内存分配
l.Formatter.(*TextFormatter).EnableColor = false

defer l.Reset()

// l.Info("msg")
// return

// output: 0 times
fmt.Println("Alloc Times:", int(testing.AllocsPerRun(100, func() {
// logger.Info("rate", "15", "low", 16, "high", 123.2, msg)
// output: 2 times
fmt.Println("Alloc Times:", int(testing.AllocsPerRun(5, func() {
// l.Info("rate", "15", "low", 16, "high", 123.2, "msg")
l.Info("msg")
})))
}
126 changes: 46 additions & 80 deletions handler/handler.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
// Package handler provide useful common log handlers.
//
// eg: file, console, multi_file, rotate_file, stream, syslog, email
package handler

import (
"bufio"
"io"
"os"
"sync"

"github.com/gookit/slog"
)

// var (
// // program pid
// pid = os.Getpid()
// // program name
// pName = filepath.Base(os.Args[0])
// hName = "unknownHost" // TODO
// // uName = "unknownUser"
// )

// defaultBufferSize sizes the buffer associated with each log file. It's large
// so that log records can accumulate without the logging thread blocking
// on disk I/O. The flushDaemon will block instead.
Expand All @@ -33,94 +24,62 @@ var (
DefaultFileFlags = os.O_CREATE | os.O_WRONLY | os.O_APPEND
)

type lockWrapper struct {
sync.Mutex
disable bool
}

// Lock it
func (lw *lockWrapper) Lock() {
if false == lw.disable {
lw.Mutex.Lock()
}
// Builder struct for create handler
type Builder struct {
Output io.Writer
Filepath string
BuffSize int
Levels []slog.Level
}

// Unlock it
func (lw *lockWrapper) Unlock() {
if !lw.disable {
lw.Mutex.Unlock()
}
// NewBuilder create
func NewBuilder() *Builder {
return &Builder{}
}

// UseLock locker
func (lw *lockWrapper) UseLock(enable bool) {
lw.disable = false == enable
// Build slog handler.
func (b *Builder) reset() {
b.Output = nil
b.Levels = b.Levels[:0]
b.Filepath = ""
b.BuffSize = 0
}

// LockEnabled status
func (lw *lockWrapper) LockEnabled() bool {
return lw.disable == false
}
// Build slog handler.
func (b *Builder) Build() slog.Handler {
defer b.reset()

// NopFlushClose no operation. provide empty Flush(), Close() methods
type NopFlushClose struct{}
if b.Output != nil {
return b.buildFromWriter(b.Output)
}

// Flush logs to disk
func (h *NopFlushClose) Flush() error {
return nil
}
if b.Filepath != "" {
f, err := QuickOpenFile(b.Filepath)
if err != nil {
panic(err)
}

// Close handler
func (h *NopFlushClose) Close() error {
return nil
}
return b.buildFromWriter(f)
}

type fileWrapper struct {
fpath string
file *os.File
panic("missing some information for build handler")
}

// func newFileHandler(fpath string) *fileWrapper {
// return &fileWrapper{fpath: fpath}
// }

// ReopenFile the log file
func (h *fileWrapper) ReopenFile() error {
if h.file != nil {
h.file.Close()
// Build slog handler.
func (b *Builder) buildFromWriter(w io.Writer) slog.Handler {
if scw, ok := w.(SyncCloseWriter); ok {
return NewSyncCloseHandler(scw, b.Levels)
}

file, err := QuickOpenFile(h.fpath)
if err != nil {
return err
if fcw, ok := w.(FlushCloseWriter); ok {
return NewFlushCloseHandler(fcw, b.Levels)
}

h.file = file
return err
}

// Write contents to *os.File
func (h *fileWrapper) Write(bts []byte) (n int, err error) {
return h.file.Write(bts)
}

// Writer return *os.File
func (h *fileWrapper) Writer() io.Writer {
return h.file
}

// Close handler, will be flush logs to file, then close file
func (h *fileWrapper) Close() error {
if err := h.Flush(); err != nil {
return err
if wc, ok := w.(io.WriteCloser); ok {
return NewWriteCloser(wc, b.Levels)
}

return h.file.Close()
}

// Flush logs to disk file
func (h *fileWrapper) Flush() error {
return h.file.Sync()
return NewIOWriter(w, b.Levels)
}

type bufFileWrapper struct {
Expand All @@ -134,6 +93,13 @@ type bufFileWrapper struct {
BuffSize int
}

// CloseBuffer for write logs
func (h *bufFileWrapper) init() {
if h.BuffSize > 0 {
// TODO create buff io
}
}

// CloseBuffer for write logs
func (h *bufFileWrapper) CloseBuffer() {
h.NoBuffer = true
Expand Down
6 changes: 1 addition & 5 deletions handler/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,11 @@ import (
"github.com/stretchr/testify/assert"
)

var doNothing = func(code int) {
// do nothing
}

func TestConsoleHandlerWithColor(t *testing.T) {
l := slog.NewWithHandlers(handler.NewConsoleHandler(slog.AllLevels))
l.Configure(func(l *slog.Logger) {
l.ReportCaller = true
l.ExitFunc = doNothing
l.ExitFunc = slog.DoNothingOnExit
})

l.Trace("this is a simple log message")
Expand Down
6 changes: 3 additions & 3 deletions handler/rotate_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,10 @@ func (h *RotateFileHandler) Handle(r *slog.Record) (err error) {
if err == nil {
h.written += uint64(n)

// do rotating file by time
// do rotate file by time
err = h.byTimeRotatingFile()

// do rotating file by size
// do rotate file by size
if h.written >= h.MaxSize {
err = h.bySizeRotatingFile()
}
Expand All @@ -147,7 +147,7 @@ func (h *RotateFileHandler) byTimeRotatingFile() error {
// rename current to new file
newFilepath := h.fpath + "." + now.Format(h.suffixFormat)

// do rotating file
// do rotate file
err := h.doRotatingFile(newFilepath)

// storage next rotating time
Expand Down
2 changes: 1 addition & 1 deletion handler/rotate_file_bytime.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
//
// EveryDay:
// - "error.log.20201223"
// EveryHour, Every30Minutes,EveryMinute:
// EveryHour, Every30Minutes, EveryMinute:
// - "error.log.20201223_1500"
// - "error.log.20201223_1530"
// - "error.log.20201223_1523"
Expand Down
2 changes: 0 additions & 2 deletions handler/iowriter.go → handler/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import (
type IOWriterHandler struct {
lockWrapper
LevelsWithFormatter

// Output io.WriteCloser
Output io.Writer
}

Expand Down

0 comments on commit e206a26

Please sign in to comment.