| 1 |
package trace |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
"os" |
| 7 |
"sync/atomic" |
| 8 |
) |
| 9 |
|
| 10 |
var ( |
| 11 |
// logger is the logger to use for tracing. |
| 12 |
logger = newLogger() |
| 13 |
|
| 14 |
// current is the targets that are enabled for tracing. |
| 15 |
current atomic.Int32 |
| 16 |
) |
| 17 |
|
| 18 |
func newLogger() *log.Logger { |
| 19 |
return log.New(os.Stderr, "", log.Ltime|log.Lmicroseconds|log.Lshortfile) |
| 20 |
} |
| 21 |
|
| 22 |
// Target is a tracing target. |
| 23 |
type Target int32 |
| 24 |
|
| 25 |
const ( |
| 26 |
// General traces general operations. |
| 27 |
General Target = 1 << iota |
| 28 |
|
| 29 |
// Packet traces git packets. |
| 30 |
Packet |
| 31 |
) |
| 32 |
|
| 33 |
// SetTarget sets the tracing targets. |
| 34 |
func SetTarget(target Target) { |
| 35 |
current.Store(int32(target)) |
| 36 |
} |
| 37 |
|
| 38 |
// SetLogger sets the logger to use for tracing. |
| 39 |
func SetLogger(l *log.Logger) { |
| 40 |
logger = l |
| 41 |
} |
| 42 |
|
| 43 |
// Print prints the given message only if the target is enabled. |
| 44 |
func (t Target) Print(args ...interface{}) { |
| 45 |
if int32(t)¤t.Load() != 0 { |
| 46 |
logger.Output(2, fmt.Sprint(args...)) // nolint: errcheck |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
// Printf prints the given message only if the target is enabled. |
| 51 |
func (t Target) Printf(format string, args ...interface{}) { |
| 52 |
if int32(t)¤t.Load() != 0 { |
| 53 |
logger.Output(2, fmt.Sprintf(format, args...)) // nolint: errcheck |
| 54 |
} |
| 55 |
} |