github.com/searKing/golang/go@v1.2.117/log/slog/record.go (about)

     1  // Copyright 2023 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slog
     6  
     7  import (
     8  	"fmt"
     9  	"log/slog"
    10  	"path"
    11  	"runtime"
    12  	"strings"
    13  )
    14  
    15  // source returns a Source for the log event.
    16  // If the Record was created without the necessary information,
    17  // or if the location is unavailable, it returns a non-nil *Source
    18  // with zero fields.
    19  func source(r slog.Record) *slog.Source {
    20  	fs := runtime.CallersFrames([]uintptr{r.PC})
    21  	f, _ := fs.Next()
    22  	return &slog.Source{
    23  		Function: f.Function,
    24  		File:     f.File,
    25  		Line:     f.Line,
    26  	}
    27  }
    28  
    29  // ShortSource returns a Source for the log event.
    30  // If the Record was created without the necessary information,
    31  // or if the location is unavailable, it returns a non-nil *Source
    32  // with zero fields.
    33  func ShortSource(r slog.Record) *slog.Source {
    34  	fs := runtime.CallersFrames([]uintptr{r.PC})
    35  	f, _ := fs.Next()
    36  
    37  	function := path.Base(f.Function)
    38  	slash := strings.LastIndex(function, ".")
    39  	if slash >= 0 && slash+1 < len(function) {
    40  		function = function[slash+1:]
    41  	}
    42  	file := path.Base(f.File)
    43  	if file == "" {
    44  		file = "???"
    45  	}
    46  	return &slog.Source{
    47  		Function: function,
    48  		File:     path.Base(f.File),
    49  		Line:     f.Line,
    50  	}
    51  }
    52  
    53  // ShortCallerPrettyfier modify the content of the function and
    54  // file keys in the data when ReportCaller is activated.
    55  // INFO[0000] main.go:23 main() hello world
    56  var ShortCallerPrettyfier = func(f *runtime.Frame) (function string, file string) {
    57  	funcname := path.Base(f.Function)
    58  	filename := path.Base(f.File)
    59  	return fmt.Sprintf("%s()", funcname), fmt.Sprintf("%s:%d", filename, f.Line)
    60  }
    61  
    62  // attrs returns the non-zero fields of s as a slice of attrs.
    63  // It is similar to a LogValue method, but we don't want Source
    64  // to implement LogValuer because it would be resolved before
    65  // the ReplaceAttr function was called.
    66  func sourceAsGroup(s *slog.Source) slog.Value {
    67  	var as []slog.Attr
    68  	if s.Function != "" {
    69  		as = append(as, slog.String("function", s.Function))
    70  	}
    71  	if s.File != "" {
    72  		as = append(as, slog.String("file", s.File))
    73  	}
    74  	if s.Line != 0 {
    75  		as = append(as, slog.Int("line", s.Line))
    76  	}
    77  	return slog.GroupValue(as...)
    78  }