pkg/logger/logger.go (75 lines of code) (raw):

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 ( "os" "strings" "go.uber.org/zap" "go.uber.org/zap/zapcore" lumberjack "gopkg.in/natefinch/lumberjack.v2" ) // Configuration stores the config for the logger type Configuration struct { LogLevel string LogLocation string } // getZapLevel converts log level string to zapcore.Level func getZapLevel(inputLogLevel string) zapcore.Level { lvl := strings.ToLower(inputLogLevel) switch lvl { case "debug": return zapcore.DebugLevel case "info": return zapcore.InfoLevel case "warn": return zapcore.WarnLevel case "error": return zapcore.ErrorLevel case "fatal": return zapcore.FatalLevel default: return zapcore.DebugLevel } } func getEncoder() zapcore.Encoder { encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder return zapcore.NewJSONEncoder(encoderConfig) } func (logConfig *Configuration) newZapLogger() *zap.Logger { //Logger { var cores []zapcore.Core logLevel := getZapLevel(logConfig.LogLevel) writer := getLogFilePath(logConfig.LogLocation) cores = append(cores, zapcore.NewCore(getEncoder(), writer, logLevel)) combinedCore := zapcore.NewTee(cores...) logger := zap.New(combinedCore, zap.AddCaller(), ) defer logger.Sync() return logger } // getLogFilePath returns the writer func getLogFilePath(logFilePath string) zapcore.WriteSyncer { var writer zapcore.WriteSyncer if logFilePath == "" { writer = zapcore.Lock(os.Stderr) } else if strings.ToLower(logFilePath) != "stdout" { writer = getLogWriter(logFilePath) } else { writer = zapcore.Lock(os.Stdout) } return writer } // getLogWriter is for lumberjack func getLogWriter(logFilePath string) zapcore.WriteSyncer { lumberJackLogger := &lumberjack.Logger{ Filename: logFilePath, MaxSize: 100, MaxBackups: 5, MaxAge: 30, Compress: true, } return zapcore.AddSync(lumberJackLogger) } // New logger initializes logger func New(logLevel, logLocation string) *zap.Logger { inputLogConfig := &Configuration{ LogLevel: logLevel, LogLocation: logLocation, } logger := inputLogConfig.newZapLogger() return logger }