github.com/orteth01/up@v0.2.0/internal/logs/text/text.go (about)

     1  // Package text implements a development-friendly textual handler.
     2  package text
     3  
     4  import (
     5  	"fmt"
     6  	"io"
     7  	"sync"
     8  
     9  	"github.com/apex/log"
    10  
    11  	"github.com/apex/up/internal/colors"
    12  )
    13  
    14  // TODO: rename since it's specific to log querying ATM
    15  // TODO: output larger timestamp when older
    16  // TODO: option to output UTC
    17  // TODO: option to output expanded fields
    18  // TODO: option to truncate
    19  
    20  // color function.
    21  type colorFunc func(string) string
    22  
    23  // omit fields.
    24  var omit = map[string]bool{
    25  	"app":    true,
    26  	"region": true,
    27  	"plugin": true,
    28  	"stage":  true,
    29  }
    30  
    31  // Colors mapping.
    32  var Colors = [...]colorFunc{
    33  	log.DebugLevel: colors.Gray,
    34  	log.InfoLevel:  colors.Blue,
    35  	log.WarnLevel:  colors.Yellow,
    36  	log.ErrorLevel: colors.Red,
    37  	log.FatalLevel: colors.Red,
    38  }
    39  
    40  // Strings mapping.
    41  var Strings = [...]string{
    42  	log.DebugLevel: "DEBU",
    43  	log.InfoLevel:  "INFO",
    44  	log.WarnLevel:  "WARN",
    45  	log.ErrorLevel: "ERRO",
    46  	log.FatalLevel: "FATA",
    47  }
    48  
    49  // Handler implementation.
    50  type Handler struct {
    51  	mu     sync.Mutex
    52  	Writer io.Writer
    53  	layout string
    54  }
    55  
    56  // New handler.
    57  func New(w io.Writer) *Handler {
    58  	return &Handler{
    59  		Writer: w,
    60  		layout: "3:04:05pm",
    61  	}
    62  }
    63  
    64  // WithFormat sets the date format.
    65  func (h *Handler) WithFormat(s string) *Handler {
    66  	h.layout = s
    67  	return h
    68  }
    69  
    70  // HandleLog implements log.Handler.
    71  func (h *Handler) HandleLog(e *log.Entry) error {
    72  	color := Colors[e.Level]
    73  	level := Strings[e.Level]
    74  	names := e.Fields.Names()
    75  
    76  	h.mu.Lock()
    77  	defer h.mu.Unlock()
    78  
    79  	ts := e.Timestamp.Local().Format(h.layout)
    80  	fmt.Fprintf(h.Writer, "  %s %s %s", colors.Gray(ts), color(level), e.Message)
    81  
    82  	for _, name := range names {
    83  		if omit[name] {
    84  			continue
    85  		}
    86  
    87  		v := e.Fields.Get(name)
    88  
    89  		if v == "" {
    90  			continue
    91  		}
    92  
    93  		fmt.Fprintf(h.Writer, " %s%s%v", color(name), colors.Gray(": "), v)
    94  	}
    95  
    96  	fmt.Fprintln(h.Writer)
    97  
    98  	return nil
    99  }