github.com/igggame/nebulas-go@v2.1.0+incompatible/util/logging/hooker_filerotate.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 "path/filepath" 24 "time" 25 26 "github.com/lestrrat/go-file-rotatelogs" 27 "github.com/rifflock/lfshook" 28 "github.com/sirupsen/logrus" 29 ) 30 31 // NewFileRotateHooker enable log file output 32 func NewFileRotateHooker(path string, age uint32) logrus.Hook { 33 if len(path) == 0 { 34 panic("Failed to parse logger folder:" + path + ".") 35 } 36 if !filepath.IsAbs(path) { 37 path, _ = filepath.Abs(path) 38 } 39 if err := os.MkdirAll(path, 0700); err != nil { 40 panic("Failed to create logger folder:" + path + ". err:" + err.Error()) 41 } 42 filePath := path + "/neb-%Y%m%d-%H.log" 43 linkPath := path + "/neb.log" 44 writer, err := rotatelogs.New( 45 filePath, 46 rotatelogs.WithLinkName(linkPath), 47 rotatelogs.WithRotationTime(time.Duration(3600)*time.Second), 48 ) 49 // set log file max age 50 if age > 0 { 51 rotatelogs.WithMaxAge(time.Duration(age) * time.Second).Configure(writer) 52 } 53 54 if err != nil { 55 panic("Failed to create rotate logs. err:" + err.Error()) 56 } 57 58 hook := lfshook.NewHook(lfshook.WriterMap{ 59 logrus.DebugLevel: writer, 60 logrus.InfoLevel: writer, 61 logrus.WarnLevel: writer, 62 logrus.ErrorLevel: writer, 63 logrus.FatalLevel: writer, 64 }, nil) 65 return hook 66 }