Skip to content

Commit

Permalink
Allow users to pass in their own logger.
Browse files Browse the repository at this point in the history
For making raft log to github.com/golang/glog, it is necessary to
specify a custom logger, because glog expects you to set the Lshortfile
flag.

Aside from this specific example, I think in general it’s better to give
users more control over the logger instead of creating it for the user —
after all, it’s still just a single line of code.
  • Loading branch information
Michael Stapelberg committed Jan 22, 2015
1 parent febcccb commit 723d32f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 7 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package raft
import (
"fmt"
"io"
"log"
"time"
)

Expand Down Expand Up @@ -65,8 +66,13 @@ type Config struct {
// step down as leader.
LeaderLeaseTimeout time.Duration

// LogOutput is used as a sink for logs. Defaults to os.Stderr.
// LogOutput is used as a sink for logs, unless Logger is specified.
// Defaults to os.Stderr.
LogOutput io.Writer

// Logger is a user-provided logger. If nil, a logger writing to LogOutput
// is used.
Logger *log.Logger
}

// DefaultConfig returns a Config with usable defaults.
Expand Down
12 changes: 9 additions & 3 deletions raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,14 @@ func NewRaft(conf *Config, fsm FSM, logs LogStore, stable StableStore, snaps Sna
}

// Ensure we have a LogOutput
if conf.LogOutput == nil {
conf.LogOutput = os.Stderr
var logger *log.Logger
if conf.Logger != nil {
logger = conf.Logger
} else {
if conf.LogOutput == nil {
conf.LogOutput = os.Stderr
}
logger = log.New(conf.LogOutput, "", log.LstdFlags)
}

// Try to restore the current term
Expand Down Expand Up @@ -200,7 +206,7 @@ func NewRaft(conf *Config, fsm FSM, logs LogStore, stable StableStore, snaps Sna
fsmSnapshotCh: make(chan *reqSnapshotFuture),
leaderCh: make(chan bool),
localAddr: localAddr,
logger: log.New(conf.LogOutput, "", log.LstdFlags),
logger: logger,
logs: logs,
peerCh: make(chan *peerFuture),
peers: peers,
Expand Down

0 comments on commit 723d32f

Please sign in to comment.