muun-recovery/utils/logger.go

79 lines
2.2 KiB
Go
Raw Normal View History

2021-01-29 16:51:08 -05:00
package utils
import (
"fmt"
2022-10-04 13:55:21 -04:00
"io"
2021-01-29 16:51:08 -05:00
"os"
"strings"
2022-10-04 13:55:21 -04:00
"time"
2021-01-29 16:51:08 -05:00
)
// DebugMode is true when the `DEBUG` environment variable is set to "true".
var DebugMode bool = os.Getenv("DEBUG") == "true"
2022-10-04 13:55:21 -04:00
var outputStream io.Writer = io.Discard
2021-01-29 16:51:08 -05:00
2022-10-04 13:55:21 -04:00
// SetOutputStream set a writer to record all logs (except Tracef).
func SetOutputStream(s io.Writer) {
outputStream = s
}
// Logger provides logging methods. Logs are written to the stream set by
// SetOutputStream. If `DebugMode` is true, we also print to stdout/stderr.
// This allows callers to log detailed information without displaying it to
// users during normal execution.
2021-01-29 16:51:08 -05:00
type Logger struct {
tag string
}
// NewLogger returns an initialized Logger instance.
func NewLogger(tag string) *Logger {
return &Logger{tag}
}
// SetTag updates the tag of this Logger.
func (l *Logger) SetTag(newTag string) {
l.tag = newTag
}
2022-10-04 13:55:21 -04:00
// Tracef works like fmt.Printf, but only prints when `DebugMode` is true. These logs
// are *not* recorded to the output stream.
func (l *Logger) Tracef(format string, v ...interface{}) {
2021-01-29 16:51:08 -05:00
if !DebugMode {
return
}
message := strings.TrimSpace(fmt.Sprintf(format, v...))
2022-10-04 13:55:21 -04:00
fmt.Printf("%s %s %s\n", time.Now().Format(time.RFC3339Nano), l.getPrefix(), message)
}
// Printf works like fmt.Printf, but only prints when `DebugMode` is true. These logs
// are recorded to the output stream, so they should not include sensitive information.
func (l *Logger) Printf(format string, v ...interface{}) {
message := strings.TrimSpace(fmt.Sprintf(format, v...))
log := fmt.Sprintf("%s %s %s\n", time.Now().Format(time.RFC3339Nano), l.getPrefix(), message)
_, _ = outputStream.Write([]byte(log))
if DebugMode {
print(log)
}
2021-01-29 16:51:08 -05:00
}
// Errorf works like fmt.Errorf, but prints the error to the console if `DebugMode` is true.
2022-10-04 13:55:21 -04:00
// These logs are recorded to the output stream, so they should not include sensitive information.
2021-01-29 16:51:08 -05:00
func (l *Logger) Errorf(format string, v ...interface{}) error {
err := fmt.Errorf(format, v...)
2022-10-04 13:55:21 -04:00
log := fmt.Sprintf("ERROR: %s %s %v\n", time.Now().Format(time.RFC3339Nano), l.getPrefix(), err)
_, _ = outputStream.Write([]byte(log))
2021-01-29 16:51:08 -05:00
if DebugMode {
2022-10-04 13:55:21 -04:00
print(log)
2021-01-29 16:51:08 -05:00
}
return err
}
func (l *Logger) getPrefix() string {
return fmt.Sprintf("[%s]", l.tag)
}