parser.go
1164 bytes
1package parser
2
3import (
4 "errors"
5 "fmt"
6 "io"
7
8 "github.com/go-logfmt/logfmt"
9
10 "github.com/TheEdgeOfRage/logfmt/config"
11)
12
13type Parser struct {
14 cfg *config.Config
15 input io.Reader
16 output io.Writer
17}
18
19func NewParser(cfg *config.Config, input io.Reader, output io.Writer) *Parser {
20 if cfg.BufferSize == 0 {
21 cfg.BufferSize = 1048576
22 }
23 return &Parser{
24 cfg: cfg,
25 input: input,
26 output: output,
27 }
28}
29
30// Start starts the parser, reading from the input stream and printing the log output to the output stream line by line
31func (p *Parser) Start() error {
32 decoder := logfmt.NewDecoderSize(p.input, p.cfg.BufferSize)
33 for decoder.ScanRecord() {
34 record, err := NewRecord(decoder, p.cfg)
35 if err != nil {
36 return err
37 }
38 if record.level < p.cfg.LogLevel {
39 continue
40 }
41 if len(p.cfg.Filter) > 0 && !record.MatchesFilter(p.cfg.Filter) {
42 continue
43 }
44 line := record.String(p.cfg)
45 if line != "" {
46 _, err = fmt.Fprintf(p.output, "%s\n", record.String(p.cfg))
47 if err != nil {
48 return fmt.Errorf("failed to print log to output: %w", err)
49 }
50 }
51 }
52
53 if errors.Is(decoder.Err(), io.EOF) {
54 return nil
55 }
56 return decoder.Err()
57}