github.com/polarismesh/polaris@v1.17.8/common/log/logger.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package log 19 20 import ( 21 "errors" 22 23 "github.com/natefinch/lumberjack" 24 "go.uber.org/zap" 25 "go.uber.org/zap/zapcore" 26 ) 27 28 // Logger 创建日志打印器 29 func Logger(file string) *zap.Logger { 30 encCfg := zapcore.EncoderConfig{ 31 MessageKey: "msg", 32 LevelKey: "level", 33 TimeKey: "time", 34 NameKey: "name", 35 CallerKey: "caller", 36 StacktraceKey: "stacktrace", 37 LineEnding: zapcore.DefaultLineEnding, 38 EncodeLevel: zapcore.LowercaseLevelEncoder, 39 EncodeTime: zapcore.ISO8601TimeEncoder, 40 EncodeDuration: zapcore.StringDurationEncoder, 41 EncodeCaller: zapcore.ShortCallerEncoder, 42 } 43 44 w := zapcore.AddSync(&lumberjack.Logger{ 45 Filename: file, 46 MaxSize: 100, // MB 47 MaxBackups: 10, 48 MaxAge: 7, // days 49 Compress: true, 50 }) 51 52 return zap.New(zapcore.NewCore(zapcore.NewConsoleEncoder(encCfg), w, zap.InfoLevel)) 53 } 54 55 func SetLogOutputLevel(scopeName string, levelName string) error { 56 scope := FindScope(scopeName) 57 if scope == nil { 58 return errors.New("invalid scope name") 59 } 60 61 l, exist := stringToLevel[levelName] 62 if !exist { 63 return errors.New("invalid log level") 64 } 65 66 lock.Lock() 67 scope.SetOutputLevel(l) 68 lock.Unlock() 69 70 return nil 71 }