github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/logcli/output/jsonl.go (about)

     1  package output
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"log"
     8  	"time"
     9  
    10  	"github.com/grafana/loki/pkg/loghttp"
    11  )
    12  
    13  // JSONLOutput prints logs and metadata as JSON Lines, suitable for scripts
    14  type JSONLOutput struct {
    15  	w       io.Writer
    16  	options *LogOutputOptions
    17  }
    18  
    19  // Format a log entry as json line
    20  func (o *JSONLOutput) FormatAndPrintln(ts time.Time, lbls loghttp.LabelSet, maxLabelsLen int, line string) {
    21  	entry := map[string]interface{}{
    22  		"timestamp": ts.In(o.options.Timezone),
    23  		"line":      line,
    24  	}
    25  
    26  	// Labels are optional
    27  	if !o.options.NoLabels {
    28  		entry["labels"] = lbls
    29  	}
    30  
    31  	out, err := json.Marshal(entry)
    32  	if err != nil {
    33  		log.Fatalf("error marshalling entry: %s", err)
    34  	}
    35  
    36  	fmt.Fprintln(o.w, string(out))
    37  }