github.com/saferwall/pe@v1.5.2/log/value.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  	"runtime"
     6  	"strconv"
     7  	"strings"
     8  	"time"
     9  )
    10  
    11  var (
    12  	defaultDepth = 3
    13  	// DefaultCaller is a Valuer that returns the file and line.
    14  	DefaultCaller = Caller(defaultDepth)
    15  
    16  	// DefaultTimestamp is a Valuer that returns the current wallclock time.
    17  	DefaultTimestamp = Timestamp(time.RFC3339)
    18  )
    19  
    20  // Valuer is returns a log value.
    21  type Valuer func(ctx context.Context) interface{}
    22  
    23  // Value return the function value.
    24  func Value(ctx context.Context, v interface{}) interface{} {
    25  	if v, ok := v.(Valuer); ok {
    26  		return v(ctx)
    27  	}
    28  	return v
    29  }
    30  
    31  // Caller returns a Valuer that returns a pkg/file:line description of the caller.
    32  func Caller(depth int) Valuer {
    33  	return func(context.Context) interface{} {
    34  		d := depth
    35  		_, file, line, _ := runtime.Caller(d)
    36  		if strings.LastIndex(file, "/log/filter.go") > 0 {
    37  			d++
    38  			_, file, line, _ = runtime.Caller(d)
    39  		}
    40  		if strings.LastIndex(file, "/log/helper.go") > 0 {
    41  			d++
    42  			_, file, line, _ = runtime.Caller(d)
    43  		}
    44  		idx := strings.LastIndexByte(file, '/')
    45  		return file[idx+1:] + ":" + strconv.Itoa(line)
    46  	}
    47  }
    48  
    49  // Timestamp returns a timestamp Valuer with a custom time format.
    50  func Timestamp(layout string) Valuer {
    51  	return func(context.Context) interface{} {
    52  		return time.Now().Format(layout)
    53  	}
    54  }
    55  
    56  func bindValues(ctx context.Context, keyvals []interface{}) {
    57  	for i := 1; i < len(keyvals); i += 2 {
    58  		if v, ok := keyvals[i].(Valuer); ok {
    59  			keyvals[i] = v(ctx)
    60  		}
    61  	}
    62  }
    63  
    64  func containsValuer(keyvals []interface{}) bool {
    65  	for i := 1; i < len(keyvals); i += 2 {
    66  		if _, ok := keyvals[i].(Valuer); ok {
    67  			return true
    68  		}
    69  	}
    70  	return false
    71  }