config: LibCxt

This is a "global" context object currently containing a cancellation
context and logger.

This struct can be considered as the lib's generic configuration, and
may be asked for in any public function.
This commit is contained in:
Paul Stemmet 2022-12-09 11:40:01 +00:00
parent 21aa140aa1
commit f0bacb8000
Signed by: Paul Stemmet
GPG Key ID: EDEA539F594E7E75
1 changed files with 58 additions and 0 deletions

58
config/context.go Normal file
View File

@ -0,0 +1,58 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package config
import (
"context"
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type LibCxt struct {
Logger *zap.Logger
Context context.Context
}
func NewLibCxt(loglevel string) *LibCxt {
return &LibCxt{
Logger: initLogger(loglevel),
Context: context.Background(),
}
}
func initLogger(ll string) *zap.Logger {
base := zap.NewProductionConfig()
base.Encoding = "console"
base.Level = zap.NewAtomicLevelAt(getLogLevel(ll))
base.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
base.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
base.DisableCaller = true
return zap.Must(base.Build())
}
func getLogLevel(ll string) zapcore.Level {
var level zapcore.Level
switch strings.ToUpper(ll) {
case "ERROR":
level = zap.ErrorLevel
case "WARN":
level = zap.WarnLevel
case "INFO":
level = zap.InfoLevel
case "DEBUG":
level = zap.DebugLevel
default:
level = zap.InfoLevel
}
return level
}