github.com/igggame/nebulas-go@v2.1.0+incompatible/util/logging/hooker_function.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  	"path/filepath"
    23  	"runtime"
    24  	"strings"
    25  
    26  	logrus "github.com/sirupsen/logrus"
    27  )
    28  
    29  type functionHooker struct {
    30  	innerLogger *logrus.Logger
    31  	file        string
    32  }
    33  
    34  func (h *functionHooker) Fire(entry *logrus.Entry) error {
    35  	pc := make([]uintptr, 10)
    36  	runtime.Callers(6, pc)
    37  	for i := 0; i < 10; i++ {
    38  		if pc[i] == 0 {
    39  			break
    40  		}
    41  		f := runtime.FuncForPC(pc[i])
    42  		file, line := f.FileLine(pc[i])
    43  		if strings.Contains(file, "sirupsen") {
    44  			continue
    45  		}
    46  		fname := f.Name()
    47  		if strings.Contains(fname, "/") {
    48  			index := strings.LastIndex(fname, "/")
    49  			entry.Data["func"] = fname[index+1:]
    50  			// entry.Data["package"] = fname[0:index]
    51  		} else {
    52  			entry.Data["func"] = fname
    53  		}
    54  		entry.Data["line"] = line
    55  		entry.Data["file"] = filepath.Base(file)
    56  		break
    57  	}
    58  	return nil
    59  }
    60  
    61  func (h *functionHooker) Levels() []logrus.Level {
    62  	return []logrus.Level{
    63  		logrus.PanicLevel,
    64  		logrus.FatalLevel,
    65  		logrus.ErrorLevel,
    66  		logrus.WarnLevel,
    67  		logrus.InfoLevel,
    68  		logrus.DebugLevel,
    69  	}
    70  }
    71  
    72  // LoadFunctionHooker loads a function hooker to the logger
    73  func LoadFunctionHooker(logger *logrus.Logger) {
    74  	_, file, _, ok := runtime.Caller(1)
    75  	if !ok {
    76  		file = "unknown"
    77  	}
    78  	inst := &functionHooker{
    79  		innerLogger: logger,
    80  		file:        file,
    81  	}
    82  	logger.Hooks.Add(inst)
    83  }