98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
package logger
|
|
|
|
import (
|
|
"io"
|
|
"os"
|
|
"time"
|
|
|
|
"git.eeqj.de/sneak/gohttpserver/internal/globals"
|
|
"github.com/rs/zerolog"
|
|
"go.uber.org/fx"
|
|
)
|
|
|
|
type LoggerParams struct {
|
|
fx.In
|
|
Globals globals.Globals
|
|
}
|
|
|
|
type Logger struct {
|
|
log *zerolog.Logger
|
|
params LoggerParams
|
|
}
|
|
|
|
func New(lc fx.Lifecycle, params LoggerParams) (*Logger, error) {
|
|
l := new(Logger)
|
|
|
|
// always log in UTC
|
|
zerolog.TimestampFunc = func() time.Time {
|
|
return time.Now().UTC()
|
|
}
|
|
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
|
|
|
tty := false
|
|
if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 {
|
|
tty = true
|
|
}
|
|
|
|
var writers []io.Writer
|
|
|
|
if tty {
|
|
// this does cool colorization for console/dev
|
|
consoleWriter := zerolog.NewConsoleWriter(
|
|
func(w *zerolog.ConsoleWriter) {
|
|
// Customize time format
|
|
w.TimeFormat = time.RFC3339Nano
|
|
},
|
|
)
|
|
|
|
writers = append(writers, consoleWriter)
|
|
} else {
|
|
// log json in prod for the machines
|
|
writers = append(writers, os.Stdout)
|
|
}
|
|
|
|
/*
|
|
// this is how you log to a file, if you do that
|
|
// sort of thing still
|
|
logfile := viper.GetString("Logfile")
|
|
if logfile != "" {
|
|
logfileDir := filepath.Dir(logfile)
|
|
err := goutil.Mkdirp(logfileDir)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("unable to create log dir")
|
|
}
|
|
|
|
hp.logfh, err = os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
|
|
if err != nil {
|
|
panic("unable to open logfile: " + err.Error())
|
|
}
|
|
|
|
writers = append(writers, hp.logfh)
|
|
*/
|
|
|
|
multi := zerolog.MultiLevelWriter(writers...)
|
|
logger := zerolog.New(multi).With().Timestamp().Logger().With().Caller().Logger()
|
|
|
|
l.log = &logger
|
|
// log.Logger = logger
|
|
|
|
return l, nil
|
|
}
|
|
|
|
func (l *Logger) EnableDebugLogging() {
|
|
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
|
l.log.Debug().Bool("debug", true).Send()
|
|
}
|
|
|
|
func (l *Logger) Get() *zerolog.Logger {
|
|
return l.log
|
|
}
|
|
|
|
func (l *Logger) Identify() {
|
|
l.log.Info().
|
|
Str("appname", l.params.Globals.Appname).
|
|
Str("version", l.params.Globals.Version).
|
|
Str("buildarch", l.params.Globals.Buildarch).
|
|
Msg("starting")
|
|
}
|