github.com/go-spring/spring-base@v1.1.3/code/code.go (about)

     1  /*
     2   * Copyright 2012-2019 the original author or authors.
     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   *      https://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 code
    18  
    19  import (
    20  	"fmt"
    21  	"runtime"
    22  	"sync"
    23  )
    24  
    25  var frameMap sync.Map
    26  
    27  func fileLine() (string, int) {
    28  	rpc := make([]uintptr, 1)
    29  	runtime.Callers(3, rpc[:])
    30  	pc := rpc[0]
    31  	if v, ok := frameMap.Load(pc); ok {
    32  		e := v.(*runtime.Frame)
    33  		return e.File, e.Line
    34  	}
    35  	frame, _ := runtime.CallersFrames(rpc).Next()
    36  	frameMap.Store(pc, &frame)
    37  	return frame.File, frame.Line
    38  }
    39  
    40  // File returns the file name of the call point.
    41  func File() string {
    42  	file, _ := fileLine()
    43  	return file
    44  }
    45  
    46  // Line returns the file line of the call point.
    47  func Line() int {
    48  	_, line := fileLine()
    49  	return line
    50  }
    51  
    52  // FileLine returns the file name and line of the call point.
    53  // In reality code.FileLine costs less time than debug.Stack.
    54  func FileLine() string {
    55  	file, line := fileLine()
    56  	return fmt.Sprintf("%s:%d", file, line)
    57  }