github.com/release-engineering/exodus-rsync@v1.11.2/internal/log/base_handler.go (about)

     1  package log
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"strings"
     8  	"sync"
     9  	"time"
    10  
    11  	apexLog "github.com/apex/log"
    12  )
    13  
    14  var stringMap = [...]string{
    15  	apexLog.DebugLevel: "DEBUG",
    16  	apexLog.InfoLevel:  "INFO",
    17  	apexLog.WarnLevel:  "WARN",
    18  	apexLog.ErrorLevel: "ERROR",
    19  	apexLog.FatalLevel: "FATAL",
    20  }
    21  
    22  type baseHandler struct {
    23  	mutex   sync.Mutex
    24  	test    bool
    25  	Writer  io.Writer
    26  	Entries []string
    27  }
    28  
    29  func newBaseHandler(w io.Writer) (*baseHandler, error) {
    30  	return &baseHandler{
    31  		Writer: w,
    32  	}, nil
    33  }
    34  
    35  func baselFields(e *apexLog.Entry) map[string]string {
    36  	out := make(map[string]string)
    37  
    38  	for key := range e.Fields {
    39  		val := fmt.Sprint(e.Fields[key])
    40  		out[key] = val
    41  	}
    42  
    43  	return out
    44  }
    45  
    46  func (h *baseHandler) HandleLog(e *apexLog.Entry) error {
    47  	bld := strings.Builder{}
    48  	bld.WriteString(e.Message + " ")
    49  
    50  	enc := json.NewEncoder(&bld)
    51  	enc.Encode(baselFields(e))
    52  
    53  	if h.test {
    54  		h.mutex.Lock()
    55  		defer h.mutex.Unlock()
    56  
    57  		h.Entries = append(h.Entries, bld.String())
    58  	}
    59  
    60  	fmt.Fprintf(h.Writer, e.Timestamp.UTC().Format(time.UnixDate)+" "+bld.String())
    61  
    62  	return nil
    63  }