Skip to content

Commit

Permalink
add async write rotate log handler
Browse files Browse the repository at this point in the history
  • Loading branch information
unclezoro committed May 20, 2020
1 parent 4fb5e5d commit 4cad318
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
16 changes: 16 additions & 0 deletions log/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io"
"net"
"os"
"path"
"reflect"
"sync"

Expand Down Expand Up @@ -70,6 +71,21 @@ func FileHandler(path string, fmtr Format) (Handler, error) {
return closingHandler{f, StreamHandler(f, fmtr)}, nil
}

// RotatingFileHandler returns a handler which writes log records to file chunks
// at the given path. When a file's size reaches the limit, the handler creates
// a new file named after the timestamp of the first log record it will contain.
func RotatingFileHandler(filePath string, limit uint, formatter Format) (Handler, error) {
if _, err := os.Stat(path.Dir(filePath)); os.IsNotExist(err) {
err := os.MkdirAll(path.Dir(filePath), 0755)
if err != nil {
return nil, fmt.Errorf("could not create directory %s, %v", path.Dir(filePath), err)
}
}
fileWriter := NewAsyncFileWriter(filePath, int64(limit))
fileWriter.Start()
return StreamHandler(fileWriter, formatter), nil
}

// NetHandler opens a socket to the given address and writes records
// over the connection.
func NetHandler(network, addr string, fmtr Format) (Handler, error) {
Expand Down
16 changes: 16 additions & 0 deletions log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,3 +243,19 @@ func (c Ctx) toArray() []interface{} {

return arr
}

func NewFileLvlHandler(logPath string, maxBytesSize uint, level string) Handler {
rfh, err := RotatingFileHandler(
logPath,
maxBytesSize,
LogfmtFormat(),
)
if err != nil {
panic(err)
}
logLevel, err := LvlFromString(level)
if err != nil {
panic(err)
}
return LvlFilterHandler(logLevel, rfh)
}

0 comments on commit 4cad318

Please sign in to comment.