...

Source file src/cdr.dev/slog/sloggers/sloghuman/sloghuman.go

Documentation: cdr.dev/slog/sloggers/sloghuman

     1  // Package sloghuman contains the slogger
     2  // that writes logs in a human readable format.
     3  package sloghuman // import "cdr.dev/slog/sloggers/sloghuman"
     4  
     5  import (
     6  	"context"
     7  	"io"
     8  	"strings"
     9  
    10  	"cdr.dev/slog"
    11  	"cdr.dev/slog/internal/entryhuman"
    12  	"cdr.dev/slog/internal/syncwriter"
    13  )
    14  
    15  // Sink creates a slog.Sink that writes logs in a human
    16  // readable YAML like format to the given writer.
    17  //
    18  // If the writer implements Sync() error then
    19  // it will be called when syncing.
    20  func Sink(w io.Writer) slog.Sink {
    21  	return &humanSink{
    22  		w:  syncwriter.New(w),
    23  		w2: w,
    24  	}
    25  }
    26  
    27  type humanSink struct {
    28  	w  *syncwriter.Writer
    29  	w2 io.Writer
    30  }
    31  
    32  func (s humanSink) LogEntry(ctx context.Context, ent slog.SinkEntry) {
    33  	str := entryhuman.Fmt(s.w2, ent)
    34  	lines := strings.Split(str, "\n")
    35  
    36  	// We need to add 4 spaces before every field line for readability.
    37  	// humanfmt doesn't do it for us because the testSink doesn't want
    38  	// it as *testing.T automatically does it.
    39  	fieldsLines := lines[1:]
    40  	for i, line := range fieldsLines {
    41  		if line == "" {
    42  			continue
    43  		}
    44  		fieldsLines[i] = strings.Repeat(" ", 2) + line
    45  	}
    46  
    47  	str = strings.Join(lines, "\n")
    48  
    49  	s.w.Write("sloghuman", []byte(str+"\n"))
    50  }
    51  
    52  func (s humanSink) Sync() {
    53  	s.w.Sync("sloghuman")
    54  }
    55  

View as plain text