github.com/dubbogo/gost@v1.14.0/log/logger/logger.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package logger
    19  
    20  import (
    21  	"github.com/natefinch/lumberjack"
    22  
    23  	"go.uber.org/zap"
    24  	"go.uber.org/zap/zapcore"
    25  )
    26  
    27  var logger Logger
    28  
    29  func init() {
    30  	InitLogger(nil)
    31  }
    32  
    33  // nolint
    34  type DubboLogger struct {
    35  	Logger
    36  	dynamicLevel zap.AtomicLevel
    37  }
    38  
    39  type Config struct {
    40  	LumberjackConfig *lumberjack.Logger `yaml:"lumberjack-config"`
    41  	ZapConfig        *zap.Config        `yaml:"zap-config"`
    42  	CallerSkip       int
    43  }
    44  
    45  // Logger is the interface for Logger types
    46  type Logger interface {
    47  	Info(args ...interface{})
    48  	Warn(args ...interface{})
    49  	Error(args ...interface{})
    50  	Debug(args ...interface{})
    51  	Fatal(args ...interface{})
    52  
    53  	Infof(fmt string, args ...interface{})
    54  	Warnf(fmt string, args ...interface{})
    55  	Errorf(fmt string, args ...interface{})
    56  	Debugf(fmt string, args ...interface{})
    57  	Fatalf(fmt string, args ...interface{})
    58  }
    59  
    60  // InitLogger use for init logger by @conf
    61  func InitLogger(conf *Config) {
    62  	var (
    63  		zapLogger *zap.Logger
    64  		config    = &Config{}
    65  	)
    66  	if conf == nil || conf.ZapConfig == nil {
    67  		zapLoggerEncoderConfig := zapcore.EncoderConfig{
    68  			TimeKey:        "time",
    69  			LevelKey:       "level",
    70  			NameKey:        "logger",
    71  			CallerKey:      "caller",
    72  			MessageKey:     "message",
    73  			StacktraceKey:  "stacktrace",
    74  			EncodeLevel:    zapcore.CapitalColorLevelEncoder,
    75  			EncodeTime:     zapcore.ISO8601TimeEncoder,
    76  			EncodeDuration: zapcore.SecondsDurationEncoder,
    77  			EncodeCaller:   zapcore.ShortCallerEncoder,
    78  		}
    79  		config.ZapConfig = &zap.Config{
    80  			Level:            zap.NewAtomicLevelAt(zap.InfoLevel),
    81  			Development:      false,
    82  			Encoding:         "console",
    83  			EncoderConfig:    zapLoggerEncoderConfig,
    84  			OutputPaths:      []string{"stdout"},
    85  			ErrorOutputPaths: []string{"stderr"},
    86  		}
    87  	} else {
    88  		config.ZapConfig = conf.ZapConfig
    89  	}
    90  
    91  	if conf != nil {
    92  		config.CallerSkip = conf.CallerSkip
    93  	}
    94  
    95  	if config.CallerSkip == 0 {
    96  		config.CallerSkip = 1
    97  	}
    98  
    99  	if conf == nil || conf.LumberjackConfig == nil {
   100  		zapLogger, _ = config.ZapConfig.Build(zap.AddCaller(), zap.AddCallerSkip(config.CallerSkip))
   101  	} else {
   102  		config.LumberjackConfig = conf.LumberjackConfig
   103  		zapLogger = initZapLoggerWithSyncer(config)
   104  	}
   105  
   106  	logger = &DubboLogger{Logger: zapLogger.Sugar(), dynamicLevel: config.ZapConfig.Level}
   107  }
   108  
   109  // SetLogger sets logger for dubbo and getty
   110  func SetLogger(log Logger) {
   111  	logger = log
   112  }
   113  
   114  // GetLogger gets the logger
   115  func GetLogger() Logger {
   116  	return logger
   117  }
   118  
   119  // SetLoggerLevel use for set logger level
   120  func SetLoggerLevel(level string) bool {
   121  	if l, ok := logger.(OpsLogger); ok {
   122  		l.SetLoggerLevel(level)
   123  		return true
   124  	}
   125  	return false
   126  }
   127  
   128  // OpsLogger use for the SetLoggerLevel
   129  type OpsLogger interface {
   130  	Logger
   131  	SetLoggerLevel(level string)
   132  }
   133  
   134  // SetLoggerLevel use for set logger level
   135  func (dl *DubboLogger) SetLoggerLevel(level string) {
   136  	l := new(zapcore.Level)
   137  	if err := l.Set(level); err == nil {
   138  		dl.dynamicLevel.SetLevel(*l)
   139  	}
   140  }
   141  
   142  // initZapLoggerWithSyncer init zap Logger with syncer
   143  func initZapLoggerWithSyncer(conf *Config) *zap.Logger {
   144  	core := zapcore.NewCore(
   145  		conf.getEncoder(),
   146  		conf.getLogWriter(),
   147  		zap.NewAtomicLevelAt(conf.ZapConfig.Level.Level()),
   148  	)
   149  
   150  	return zap.New(core, zap.AddCaller(), zap.AddCallerSkip(conf.CallerSkip))
   151  }
   152  
   153  // getEncoder get encoder by config, zapcore support json and console encoder
   154  func (c *Config) getEncoder() zapcore.Encoder {
   155  	if c.ZapConfig.Encoding == "json" {
   156  		return zapcore.NewJSONEncoder(c.ZapConfig.EncoderConfig)
   157  	} else if c.ZapConfig.Encoding == "console" {
   158  		return zapcore.NewConsoleEncoder(c.ZapConfig.EncoderConfig)
   159  	}
   160  	return nil
   161  }
   162  
   163  // getLogWriter get Lumberjack writer by LumberjackConfig
   164  func (c *Config) getLogWriter() zapcore.WriteSyncer {
   165  	return zapcore.AddSync(c.LumberjackConfig)
   166  }