Add logger
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
2022-01-15 22:32:24 +01:00
parent 3bf0821c34
commit f7cdbb8722
4 changed files with 113 additions and 5 deletions

View File

@@ -6,10 +6,13 @@ import (
"net/http"
"os"
"os/signal"
"strings"
"time"
"git.t-juice.club/torjus/gpaste"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
@@ -51,13 +54,15 @@ func ActionServe(c *cli.Context) error {
if err != nil {
return cli.Exit(err, 1)
}
// Setup loggers
rootLogger := getRootLogger(cfg.LogLevel)
serverLogger := rootLogger.Named("SERV")
// Setup contexts for clean shutdown
rootCtx, rootCancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer rootCancel()
httpCtx, httpCancel := context.WithCancel(rootCtx)
defer httpCancel()
httpShutdownCtx, httpShutdownCancel := context.WithCancel(context.Background())
defer httpShutdownCancel()
@@ -72,12 +77,50 @@ func ActionServe(c *cli.Context) error {
defer cancel()
srv.Shutdown(timeoutCtx)
}()
serverLogger.Infow("Starting HTTP server.", "addr", cfg.ListenAddr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("Error: %s\n", err)
serverLogger.Errorw("Error during shutdown.", "error", err)
}
serverLogger.Infow("HTTP server shutdown complete.", "addr", cfg.ListenAddr)
httpShutdownCancel()
}()
<-httpShutdownCtx.Done()
return nil
}
func getRootLogger(level string) *zap.SugaredLogger {
logEncoderConfig := zap.NewProductionEncoderConfig()
logEncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
logEncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
logEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logEncoderConfig.EncodeDuration = zapcore.StringDurationEncoder
rootLoggerConfig := &zap.Config{
Level: zap.NewAtomicLevelAt(zap.DebugLevel),
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stdout"},
Encoding: "console",
EncoderConfig: logEncoderConfig,
DisableCaller: true,
}
switch strings.ToUpper(level) {
case "DEBUG":
rootLoggerConfig.DisableCaller = false
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
case "INFO":
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
case "WARN", "WARNING":
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.WarnLevel)
case "ERR", "ERROR":
rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.ErrorLevel)
}
rootLogger, err := rootLoggerConfig.Build()
if err != nil {
panic(err)
}
return rootLogger.Sugar()
}