Skip to content

Commit

Permalink
Add support for log rotation
Browse files Browse the repository at this point in the history
When using debug level the log files tends to fill up quickly.
Add support for log rotation using lumberjack, simple and easy to use
log rotation module.

Signed-off-by: Shahar Klein <sklein@nvidia.com>
  • Loading branch information
shahar-klein committed Jun 16, 2020
1 parent 3882e40 commit 7404bdf
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require (
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b
google.golang.org/grpc v1.23.0
gopkg.in/yaml.v2 v2.2.8 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0
k8s.io/api v0.0.0-20181115043458-b799cb063522
k8s.io/apimachinery v0.0.0-20181110190943-2a7c93004028
k8s.io/client-go v0.0.0-20181115111358-9bea17718df8
Expand Down
28 changes: 18 additions & 10 deletions logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ import (
"os"
"strings"
"time"
"io"

"github.com/pkg/errors"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)

// Level type
Expand All @@ -37,7 +39,7 @@ const (
)

var loggingStderr bool
var loggingFp *os.File
var loggingW io.Writer
var loggingLevel Level

const defaultTimestampFormat = time.RFC3339
Expand Down Expand Up @@ -69,10 +71,10 @@ func printf(level Level, format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, "\n")
}

if loggingFp != nil {
fmt.Fprintf(loggingFp, header, t.Format(defaultTimestampFormat), level)
fmt.Fprintf(loggingFp, format, a...)
fmt.Fprintf(loggingFp, "\n")
if loggingW != nil {
fmt.Fprintf(loggingW, header, t.Format(defaultTimestampFormat), level)
fmt.Fprintf(loggingW, format, a...)
fmt.Fprintf(loggingW, "\n")
}
}

Expand Down Expand Up @@ -139,16 +141,22 @@ func SetLogFile(filename string) {
return
}

fp, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
loggingFp = nil
w := &lumberjack.Logger{
Filename: filename,
MaxSize: 100, // megabytes
MaxBackups: 5,
MaxAge: 5, // days
Compress: true,
}
if w == nil {
fmt.Fprintf(os.Stderr, "multus logging: cannot open %s", filename)
}
loggingFp = fp
loggingW = w

}

func init() {
loggingStderr = true
loggingFp = nil
loggingW = nil
loggingLevel = PanicLevel
}

0 comments on commit 7404bdf

Please sign in to comment.