github.com/braveheart12/insolar-09-08-19@v0.8.7/log/sourceinfo.go (about)

     1  /*
     2   *    Copyright 2019 Insolar Technologies
     3   *
     4   *    Licensed under the Apache License, Version 2.0 (the "License");
     5   *    you may not use this file except in compliance with the License.
     6   *    You may obtain a copy of the License at
     7   *
     8   *        http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   *    Unless required by applicable law or agreed to in writing, software
    11   *    distributed under the License is distributed on an "AS IS" BASIS,
    12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   *    See the License for the specific language governing permissions and
    14   *    limitations under the License.
    15   */
    16  
    17  package log
    18  
    19  import (
    20  	"path"
    21  	"runtime"
    22  	"strings"
    23  )
    24  
    25  // callInfo bundles the info about the call environment
    26  // when a logging statement occurred.
    27  type callInfo struct {
    28  	packageName string
    29  	fileName    string
    30  	funcName    string
    31  	line        int
    32  }
    33  
    34  func getCallInfo(skipCallNumber int) *callInfo {
    35  	pc, file, line, _ := runtime.Caller(skipCallNumber)
    36  	_, fileName := path.Split(file)
    37  	parts := strings.Split(runtime.FuncForPC(pc).Name(), ".")
    38  	pl := len(parts)
    39  	packageName := ""
    40  	funcName := parts[pl-1]
    41  
    42  	if pl > 1 && parts[pl-2][0] == '(' {
    43  		funcName = parts[pl-2] + "." + funcName
    44  		packageName = strings.Join(parts[0:pl-2], ".")
    45  	} else {
    46  		packageName = strings.Join(parts[0:pl-1], ".")
    47  	}
    48  
    49  	return &callInfo{
    50  		packageName: stripPackageName(packageName),
    51  		fileName:    fileName,
    52  		funcName:    funcName,
    53  		line:        line,
    54  	}
    55  }
    56  
    57  func stripPackageName(packageName string) string {
    58  	result := strings.TrimPrefix(packageName, "github.com/insolar/insolar/")
    59  	i := strings.Index(result, ".")
    60  	if result == packageName || i == -1 {
    61  		return result
    62  	}
    63  	return result[:i]
    64  }