package logging
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
log "github.com/Sirupsen/logrus"
|
|
|
|
"cygnux.net/kepler/config"
|
|
)
|
|
|
|
const DefaultFormat = "TEXT"
|
|
|
|
var OutputFile *os.File
|
|
|
|
type PlainFormatter struct {
|
|
}
|
|
|
|
func (pf *PlainFormatter) Format(entry *log.Entry) ([]byte, error) {
|
|
bytes := []byte(fmt.Sprintf("[%s %s] %s\n", entry.Time.Format(time.RFC3339), strings.ToUpper(entry.Level.String()), entry.Message))
|
|
return bytes, nil
|
|
}
|
|
|
|
func InitializeLogging(cfg config.Config, useStd bool, level ...string) error {
|
|
if nil == cfg {
|
|
cfg = config.MakeVConfig(nil)
|
|
}
|
|
var lvl = log.DebugLevel
|
|
if len(level) > 0 {
|
|
lvl, _ = log.ParseLevel(level[0])
|
|
} else {
|
|
lvl, _ = log.ParseLevel(cfg.GetString("level", "DEBUG"))
|
|
}
|
|
|
|
if useStd || cfg.GetString("filename") == "" {
|
|
log.SetOutput(os.Stdout)
|
|
OutputFile = nil
|
|
} else {
|
|
f, e := os.OpenFile(cfg.GetString("filename"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
|
|
if nil != e {
|
|
_ = fmt.Errorf("Open file <%s> for logging failed<%v>!\n", cfg.GetString("filename"), e)
|
|
return e
|
|
} else {
|
|
log.SetOutput(f)
|
|
OutputFile = f
|
|
}
|
|
}
|
|
if strings.ToLower(cfg.GetString("format")) == "json" {
|
|
log.SetFormatter(&log.JSONFormatter{})
|
|
} else {
|
|
log.SetFormatter(&PlainFormatter{})
|
|
}
|
|
log.SetLevel(lvl)
|
|
//log.Info("Logging Initialized.")
|
|
return nil
|
|
}
|
|
|
|
func DeinitializeLogging() {
|
|
if nil != OutputFile {
|
|
_ = OutputFile.Close()
|
|
}
|
|
}
|