...

Source file src/github.com/go-logfmt/logfmt/example_test.go

Documentation: github.com/go-logfmt/logfmt

     1  package logfmt_test
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/go-logfmt/logfmt"
    11  )
    12  
    13  func ExampleEncoder() {
    14  	check := func(err error) {
    15  		if err != nil {
    16  			panic(err)
    17  		}
    18  	}
    19  
    20  	e := logfmt.NewEncoder(os.Stdout)
    21  
    22  	check(e.EncodeKeyval("id", 1))
    23  	check(e.EncodeKeyval("dur", time.Second+time.Millisecond))
    24  	check(e.EndRecord())
    25  
    26  	check(e.EncodeKeyval("id", 1))
    27  	check(e.EncodeKeyval("path", "/path/to/file"))
    28  	check(e.EncodeKeyval("err", errors.New("file not found")))
    29  	check(e.EndRecord())
    30  
    31  	// Output:
    32  	// id=1 dur=1.001s
    33  	// id=1 path=/path/to/file err="file not found"
    34  }
    35  
    36  func ExampleDecoder() {
    37  	in := `
    38  id=1 dur=1.001s
    39  id=1 path=/path/to/file err="file not found"
    40  `
    41  
    42  	d := logfmt.NewDecoder(strings.NewReader(in))
    43  	for d.ScanRecord() {
    44  		for d.ScanKeyval() {
    45  			fmt.Printf("k: %s v: %s\n", d.Key(), d.Value())
    46  		}
    47  		fmt.Println()
    48  	}
    49  	if d.Err() != nil {
    50  		panic(d.Err())
    51  	}
    52  
    53  	// Output:
    54  	// k: id v: 1
    55  	// k: dur v: 1.001s
    56  	//
    57  	// k: id v: 1
    58  	// k: path v: /path/to/file
    59  	// k: err v: file not found
    60  }
    61  

View as plain text