2016-09-30 21:37:56 +00:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"os"
|
2017-04-12 17:41:26 +00:00
|
|
|
"regexp"
|
2016-10-11 12:06:17 +00:00
|
|
|
"time"
|
2016-09-30 21:37:56 +00:00
|
|
|
|
|
|
|
"github.com/influxdata/wlog"
|
|
|
|
)
|
|
|
|
|
2017-04-12 17:41:26 +00:00
|
|
|
var prefixRegex = regexp.MustCompile("^[DIWE]!")
|
|
|
|
|
2016-09-30 21:37:56 +00:00
|
|
|
// newTelegrafWriter returns a logging-wrapped writer.
|
|
|
|
func newTelegrafWriter(w io.Writer) io.Writer {
|
|
|
|
return &telegrafLog{
|
|
|
|
writer: wlog.NewWriter(w),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type telegrafLog struct {
|
|
|
|
writer io.Writer
|
|
|
|
}
|
|
|
|
|
2016-10-11 12:06:17 +00:00
|
|
|
func (t *telegrafLog) Write(b []byte) (n int, err error) {
|
2017-04-12 17:41:26 +00:00
|
|
|
var line []byte
|
|
|
|
if !prefixRegex.Match(b) {
|
|
|
|
line = append([]byte(time.Now().UTC().Format(time.RFC3339)+" I! "), b...)
|
|
|
|
} else {
|
|
|
|
line = append([]byte(time.Now().UTC().Format(time.RFC3339)+" "), b...)
|
|
|
|
}
|
|
|
|
return t.writer.Write(line)
|
2016-09-30 21:37:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetupLogging configures the logging output.
|
|
|
|
// debug will set the log level to DEBUG
|
|
|
|
// quiet will set the log level to ERROR
|
|
|
|
// logfile will direct the logging output to a file. Empty string is
|
2016-10-12 14:37:51 +00:00
|
|
|
// interpreted as stderr. If there is an error opening the file the
|
|
|
|
// logger will fallback to stderr.
|
2016-09-30 21:37:56 +00:00
|
|
|
func SetupLogging(debug, quiet bool, logfile string) {
|
2016-10-11 12:06:17 +00:00
|
|
|
log.SetFlags(0)
|
2016-09-30 21:37:56 +00:00
|
|
|
if debug {
|
|
|
|
wlog.SetLevel(wlog.DEBUG)
|
|
|
|
}
|
|
|
|
if quiet {
|
|
|
|
wlog.SetLevel(wlog.ERROR)
|
|
|
|
}
|
|
|
|
|
|
|
|
var oFile *os.File
|
|
|
|
if logfile != "" {
|
|
|
|
if _, err := os.Stat(logfile); os.IsNotExist(err) {
|
|
|
|
if oFile, err = os.Create(logfile); err != nil {
|
2016-10-12 14:37:51 +00:00
|
|
|
log.Printf("E! Unable to create %s (%s), using stderr", logfile, err)
|
|
|
|
oFile = os.Stderr
|
2016-09-30 21:37:56 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if oFile, err = os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil {
|
2016-10-12 14:37:51 +00:00
|
|
|
log.Printf("E! Unable to append to %s (%s), using stderr", logfile, err)
|
|
|
|
oFile = os.Stderr
|
2016-09-30 21:37:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2016-10-12 14:37:51 +00:00
|
|
|
oFile = os.Stderr
|
2016-09-30 21:37:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
log.SetOutput(newTelegrafWriter(oFile))
|
|
|
|
}
|