github.com/aclements/go-misc@v0.0.0-20240129233631-2f6ede80790c/go-weave/weave/trace.go (about)

     1  // Copyright 2016 The Go Authors. 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 weave
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  )
    11  
    12  type traceEntry struct {
    13  	tid int
    14  	msg string
    15  }
    16  
    17  func (s *Scheduler) Trace(msg string) {
    18  	s.trace = append(s.trace, traceEntry{s.curThread.id, msg})
    19  }
    20  
    21  func (s *Scheduler) Tracef(msg string, args ...interface{}) {
    22  	s.trace = append(s.trace, traceEntry{s.curThread.id, fmt.Sprintf(msg, args...)})
    23  }
    24  
    25  type errorWithTrace struct {
    26  	err   interface{}
    27  	trace []traceEntry
    28  }
    29  
    30  func (e errorWithTrace) Error() string {
    31  	if len(e.trace) == 0 {
    32  		return fmt.Sprint(e.err)
    33  	}
    34  
    35  	var buf bytes.Buffer
    36  	fmt.Fprintf(&buf, "%v\n", e.err)
    37  	fmt.Fprintf(&buf, "trace:")
    38  	for _, ent := range e.trace {
    39  		fmt.Fprintf(&buf, "\n  T%d %s", ent.tid, ent.msg)
    40  	}
    41  	return buf.String()
    42  }