github.com/blend/go-sdk@v1.20220411.3/vault/event.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package vault
     9  
    10  import (
    11  	"context"
    12  	"fmt"
    13  	"io"
    14  	"net/http"
    15  	"strings"
    16  	"time"
    17  
    18  	"github.com/blend/go-sdk/ansi"
    19  	"github.com/blend/go-sdk/logger"
    20  	"github.com/blend/go-sdk/timeutil"
    21  )
    22  
    23  var (
    24  	_ logger.Event        = (*Event)(nil)
    25  	_ logger.TextWritable = (*Event)(nil)
    26  	_ logger.JSONWritable = (*Event)(nil)
    27  )
    28  
    29  const (
    30  	// Flag is the logger flag.
    31  	Flag = "vault"
    32  )
    33  
    34  // NewEventListener returns a new logger listener for a given event.
    35  func NewEventListener(action func(context.Context, Event)) logger.Listener {
    36  	return func(ctx context.Context, e logger.Event) {
    37  		if typed, ok := e.(Event); ok {
    38  			action(ctx, typed)
    39  		}
    40  	}
    41  }
    42  
    43  // NewEvent returns a new event from a request.
    44  func NewEvent(req *http.Request) *Event {
    45  	return &Event{
    46  		Remote: req.URL.Host,
    47  		Method: req.Method,
    48  		Path:   strings.TrimPrefix(req.URL.Path, "/v1/"),
    49  	}
    50  }
    51  
    52  // Event is an event.
    53  type Event struct {
    54  	Remote     string
    55  	Method     string
    56  	Path       string
    57  	StatusCode int
    58  	Elapsed    time.Duration
    59  }
    60  
    61  // GetFlag implements logger.Event.
    62  func (e Event) GetFlag() string { return Flag }
    63  
    64  // WriteText writes text for the event.
    65  func (e *Event) WriteText(tf logger.TextFormatter, wr io.Writer) {
    66  	fmt.Fprint(wr, "["+tf.Colorize(e.Method, ansi.ColorBlue)+"]")
    67  	fmt.Fprint(wr, logger.Space)
    68  	fmt.Fprint(wr, e.Remote)
    69  	fmt.Fprint(wr, logger.Space)
    70  	fmt.Fprint(wr, e.Path)
    71  	fmt.Fprint(wr, logger.Space)
    72  	fmt.Fprint(wr, e.StatusCode)
    73  	fmt.Fprint(wr, logger.Space)
    74  	fmt.Fprint(wr, e.Elapsed)
    75  }
    76  
    77  // Decompose impements logger.JSONWritable.
    78  func (e *Event) Decompose() map[string]interface{} {
    79  	return map[string]interface{}{
    80  		"remote":     e.Remote,
    81  		"method":     e.Method,
    82  		"path":       e.Path,
    83  		"statusCode": e.StatusCode,
    84  		"elapsed":    timeutil.Milliseconds(e.Elapsed),
    85  	}
    86  }