github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/smalltrace.go (about)

     1  // Copyright 2016 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package util
    12  
    13  import (
    14  	"runtime"
    15  	"strconv"
    16  	"strings"
    17  )
    18  
    19  var prefix = func() string {
    20  	result := "github.com/cockroachdb/cockroach/pkg/"
    21  	if runtime.Compiler == "gccgo" {
    22  		result = strings.Replace(result, ".", "_", -1)
    23  		result = strings.Replace(result, "/", "_", -1)
    24  	}
    25  	return result
    26  }()
    27  
    28  // GetSmallTrace returns a comma-separated string containing the top
    29  // 5 callers from a given skip level.
    30  func GetSmallTrace(skip int) string {
    31  	var pcs [5]uintptr
    32  	nCallers := runtime.Callers(skip, pcs[:])
    33  	callers := make([]string, 0, nCallers)
    34  	frames := runtime.CallersFrames(pcs[:])
    35  
    36  	for {
    37  		f, more := frames.Next()
    38  		function := strings.TrimPrefix(f.Function, prefix)
    39  		file := f.File
    40  		if index := strings.LastIndexByte(file, '/'); index >= 0 {
    41  			file = file[index+1:]
    42  		}
    43  		callers = append(callers, file+":"+strconv.Itoa(f.Line)+":"+function)
    44  		if !more {
    45  			break
    46  		}
    47  	}
    48  
    49  	return strings.Join(callers, ",")
    50  }