github.com/observiq/carbon@v0.9.11-0.20200820160507-1b872e368a5e/operator/builtin/output/stdout.go (about)

     1  package output
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"io"
     7  	"os"
     8  	"sync"
     9  
    10  	"github.com/observiq/carbon/entry"
    11  	"github.com/observiq/carbon/operator"
    12  	"github.com/observiq/carbon/operator/helper"
    13  )
    14  
    15  // Stdout is a global handle to standard output
    16  var Stdout io.Writer = os.Stdout
    17  
    18  func init() {
    19  	operator.Register("stdout", func() operator.Builder { return NewStdoutConfig("") })
    20  }
    21  
    22  func NewStdoutConfig(operatorID string) *StdoutConfig {
    23  	return &StdoutConfig{
    24  		OutputConfig: helper.NewOutputConfig(operatorID, "stdout"),
    25  	}
    26  }
    27  
    28  // StdoutConfig is the configuration of the Stdout operator
    29  type StdoutConfig struct {
    30  	helper.OutputConfig `yaml:",inline"`
    31  }
    32  
    33  // Build will build a stdout operator.
    34  func (c StdoutConfig) Build(context operator.BuildContext) (operator.Operator, error) {
    35  	outputOperator, err := c.OutputConfig.Build(context)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	return &StdoutOperator{
    41  		OutputOperator: outputOperator,
    42  		encoder:        json.NewEncoder(Stdout),
    43  	}, nil
    44  }
    45  
    46  // StdoutOperator is an operator that logs entries using stdout.
    47  type StdoutOperator struct {
    48  	helper.OutputOperator
    49  	encoder *json.Encoder
    50  	mux     sync.Mutex
    51  }
    52  
    53  // Process will log entries received.
    54  func (o *StdoutOperator) Process(ctx context.Context, entry *entry.Entry) error {
    55  	o.mux.Lock()
    56  	err := o.encoder.Encode(entry)
    57  	if err != nil {
    58  		o.mux.Unlock()
    59  		o.Errorf("Failed to process entry: %s, $s", err, entry.Record)
    60  		return err
    61  	}
    62  	o.mux.Unlock()
    63  	return nil
    64  }