Files
flagger/pkg/logger/logger.go
Stefan Prodan cd75c5fa25 Copyright Flux authors
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
2020-12-21 19:44:52 +02:00

80 lines
2.3 KiB
Go

/*
Copyright 2020 The Flux authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package logger
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// NewLogger returns a zap sugared logger configured with json format and caller id
func NewLogger(logLevel string) (*zap.SugaredLogger, error) {
return NewLoggerWithEncoding(logLevel, "json")
}
// NewLoggerWithEncoding returns a zap sugared logger configured with provided format, e.g. console or json, and caller id
func NewLoggerWithEncoding(logLevel, zapEncoding string) (*zap.SugaredLogger, error) {
level := zap.NewAtomicLevelAt(zapcore.InfoLevel)
switch logLevel {
case "debug":
level = zap.NewAtomicLevelAt(zapcore.DebugLevel)
case "info":
level = zap.NewAtomicLevelAt(zapcore.InfoLevel)
case "warn":
level = zap.NewAtomicLevelAt(zapcore.WarnLevel)
case "error":
level = zap.NewAtomicLevelAt(zapcore.ErrorLevel)
case "fatal":
level = zap.NewAtomicLevelAt(zapcore.FatalLevel)
case "panic":
level = zap.NewAtomicLevelAt(zapcore.PanicLevel)
}
zapEncoderConfig := zapcore.EncoderConfig{
TimeKey: "ts",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
zapConfig := zap.Config{
Level: level,
Development: false,
Sampling: &zap.SamplingConfig{
Initial: 100,
Thereafter: 100,
},
Encoding: zapEncoding,
EncoderConfig: zapEncoderConfig,
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
logger, err := zapConfig.Build()
if err != nil {
return nil, err
}
return logger.Sugar(), nil
}