Skip to content

Commit

Permalink
smtp: Use zerolog hooks for warns/errors expvars #90
Browse files Browse the repository at this point in the history
  • Loading branch information
jhillyerd committed Mar 31, 2018
1 parent 92f2da5 commit e076f80
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 22 deletions.
4 changes: 3 additions & 1 deletion pkg/server/smtp/handler.go
Expand Up @@ -113,7 +113,9 @@ func (s *Session) String() string {
* 5. Goto 2
*/
func (s *Server) startSession(id int, conn net.Conn) {
logger := log.With().Str("module", "smtp").Str("remote", conn.RemoteAddr().String()).
logger := log.Hook(logHook{}).With().
Str("module", "smtp").
Str("remote", conn.RemoteAddr().String()).
Int("session", id).Logger()
logger.Info().Msg("Starting SMTP session")
expConnectsCurrent.Add(1)
Expand Down
42 changes: 21 additions & 21 deletions pkg/server/smtp/listener.go
Expand Up @@ -36,6 +36,27 @@ func init() {
})
}

var (
// Raw stat collectors
expConnectsTotal = new(expvar.Int)
expConnectsCurrent = new(expvar.Int)
expReceivedTotal = new(expvar.Int)
expErrorsTotal = new(expvar.Int)
expWarnsTotal = new(expvar.Int)

// History of certain stats
deliveredHist = list.New()
connectsHist = list.New()
errorsHist = list.New()
warnsHist = list.New()

// History rendered as comma delim string
expReceivedHist = new(expvar.String)
expConnectsHist = new(expvar.String)
expErrorsHist = new(expvar.String)
expWarnsHist = new(expvar.String)
)

// Server holds the configuration and state of our SMTP server
type Server struct {
// TODO(#91) Refactor config items out of this struct
Expand All @@ -59,27 +80,6 @@ type Server struct {
waitgroup *sync.WaitGroup // Waitgroup tracks individual sessions
}

var (
// Raw stat collectors
expConnectsTotal = new(expvar.Int)
expConnectsCurrent = new(expvar.Int)
expReceivedTotal = new(expvar.Int)
expErrorsTotal = new(expvar.Int)
expWarnsTotal = new(expvar.Int)

// History of certain stats
deliveredHist = list.New()
connectsHist = list.New()
errorsHist = list.New()
warnsHist = list.New()

// History rendered as comma delim string
expReceivedHist = new(expvar.String)
expConnectsHist = new(expvar.String)
expErrorsHist = new(expvar.String)
expWarnsHist = new(expvar.String)
)

// NewServer creates a new Server instance with the specificed config
func NewServer(
cfg config.SMTP,
Expand Down
15 changes: 15 additions & 0 deletions pkg/server/smtp/loghook.go
@@ -0,0 +1,15 @@
package smtp

import "github.com/rs/zerolog"

type logHook struct{}

// Run implements a zerolog hook that updates the SMTP warning/error expvars.
func (h logHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
switch level {
case zerolog.WarnLevel:
expWarnsTotal.Add(1)
case zerolog.ErrorLevel:
expErrorsTotal.Add(1)
}
}

0 comments on commit e076f80

Please sign in to comment.