github.com/maier/nomad@v0.4.1-0.20161110003312-a9e3d0b8549d/command/agent/syslog.go (about)

     1  package agent
     2  
     3  import (
     4  	"bytes"
     5  	"github.com/hashicorp/go-syslog"
     6  	"github.com/hashicorp/logutils"
     7  )
     8  
     9  // levelPriority is used to map a log level to a
    10  // syslog priority level
    11  var levelPriority = map[string]gsyslog.Priority{
    12  	"TRACE": gsyslog.LOG_DEBUG,
    13  	"DEBUG": gsyslog.LOG_INFO,
    14  	"INFO":  gsyslog.LOG_NOTICE,
    15  	"WARN":  gsyslog.LOG_WARNING,
    16  	"ERR":   gsyslog.LOG_ERR,
    17  	"CRIT":  gsyslog.LOG_CRIT,
    18  }
    19  
    20  // SyslogWrapper is used to cleaup log messages before
    21  // writing them to a Syslogger. Implements the io.Writer
    22  // interface.
    23  type SyslogWrapper struct {
    24  	l    gsyslog.Syslogger
    25  	filt *logutils.LevelFilter
    26  }
    27  
    28  // Write is used to implement io.Writer
    29  func (s *SyslogWrapper) Write(p []byte) (int, error) {
    30  	// Skip syslog if the log level doesn't apply
    31  	if !s.filt.Check(p) {
    32  		return 0, nil
    33  	}
    34  
    35  	// Extract log level
    36  	var level string
    37  	afterLevel := p
    38  	x := bytes.IndexByte(p, '[')
    39  	if x >= 0 {
    40  		y := bytes.IndexByte(p[x:], ']')
    41  		if y >= 0 {
    42  			level = string(p[x+1 : x+y])
    43  			afterLevel = p[x+y+2:]
    44  		}
    45  	}
    46  
    47  	// Each log level will be handled by a specific syslog priority
    48  	priority, ok := levelPriority[level]
    49  	if !ok {
    50  		priority = gsyslog.LOG_NOTICE
    51  	}
    52  
    53  	// Attempt the write
    54  	err := s.l.WriteLevel(priority, afterLevel)
    55  	return len(p), err
    56  }