github.com/igggame/nebulas-go@v2.1.0+incompatible/util/logging/loggers.go (about) 1 // Copyright (C) 2017 go-nebulas authors 2 // 3 // This file is part of the go-nebulas library. 4 // 5 // the go-nebulas library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // the go-nebulas library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 19 package logging 20 21 import ( 22 "os" 23 24 "github.com/sirupsen/logrus" 25 ) 26 27 // const 28 const ( 29 PanicLevel = "panic" 30 FatalLevel = "fatal" 31 ErrorLevel = "error" 32 WarnLevel = "warn" 33 InfoLevel = "info" 34 DebugLevel = "debug" 35 ) 36 37 type emptyWriter struct{} 38 39 func (ew emptyWriter) Write(p []byte) (int, error) { 40 return 0, nil 41 } 42 43 var clog *logrus.Logger 44 var vlog *logrus.Logger 45 46 // CLog return console logger 47 func CLog() *logrus.Logger { 48 if clog == nil { 49 Init("/tmp", "info", 0) 50 } 51 return clog 52 } 53 54 // VLog return verbose logger 55 func VLog() *logrus.Logger { 56 if vlog == nil { 57 Init("/tmp", "info", 0) 58 } 59 return vlog 60 } 61 62 func convertLevel(level string) logrus.Level { 63 switch level { 64 case PanicLevel: 65 return logrus.PanicLevel 66 case FatalLevel: 67 return logrus.FatalLevel 68 case ErrorLevel: 69 return logrus.ErrorLevel 70 case WarnLevel: 71 return logrus.WarnLevel 72 case InfoLevel: 73 return logrus.InfoLevel 74 case DebugLevel: 75 return logrus.DebugLevel 76 default: 77 return logrus.InfoLevel 78 } 79 } 80 81 // Init loggers 82 func Init(path string, level string, age uint32) { 83 fileHooker := NewFileRotateHooker(path, age) 84 85 clog = logrus.New() 86 LoadFunctionHooker(clog) 87 clog.Hooks.Add(fileHooker) 88 clog.Out = os.Stdout 89 clog.Formatter = &logrus.TextFormatter{FullTimestamp: true} 90 clog.Level = convertLevel("debug") 91 92 vlog = logrus.New() 93 LoadFunctionHooker(vlog) 94 vlog.Hooks.Add(fileHooker) 95 vlog.Out = &emptyWriter{} 96 vlog.Formatter = &logrus.TextFormatter{FullTimestamp: true} 97 vlog.Level = convertLevel(level) 98 99 VLog().WithFields(logrus.Fields{ 100 "path": path, 101 "level": level, 102 }).Info("Logger Configuration.") 103 }