github.com/facebookincubator/go-belt@v0.0.0-20230703220935-39cd348f1a38/examples/everything/main.go (about)

     1  // Copyright 2022 Meta Platforms, Inc. and affiliates.
     2  //
     3  // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
     4  //
     5  // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
     6  //
     7  // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
     8  //
     9  // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
    10  //
    11  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    12  
    13  package main
    14  
    15  import (
    16  	"bytes"
    17  	"context"
    18  	"fmt"
    19  	"net/http"
    20  	_ "net/http/pprof"
    21  	"os"
    22  
    23  	"github.com/facebookincubator/go-belt"
    24  	"github.com/facebookincubator/go-belt/beltctx"
    25  	"github.com/facebookincubator/go-belt/pkg/field"
    26  	"github.com/facebookincubator/go-belt/tool/experimental/errmon"
    27  	errmonlogger "github.com/facebookincubator/go-belt/tool/experimental/errmon/implementation/logger"
    28  	"github.com/facebookincubator/go-belt/tool/experimental/metrics"
    29  	prometheusadapter "github.com/facebookincubator/go-belt/tool/experimental/metrics/implementation/prometheus"
    30  	"github.com/facebookincubator/go-belt/tool/experimental/tracer"
    31  	"github.com/facebookincubator/go-belt/tool/experimental/tracer/implementation/zipkin"
    32  	"github.com/facebookincubator/go-belt/tool/logger"
    33  	"github.com/facebookincubator/go-belt/tool/logger/implementation/zap"
    34  	"github.com/prometheus/client_golang/prometheus"
    35  	"github.com/prometheus/common/expfmt"
    36  )
    37  
    38  func main() {
    39  	ctx := context.Background()
    40  
    41  	ctx = logger.CtxWithLogger(ctx, zap.Default())
    42  	ctx = metrics.CtxWithMetrics(ctx, prometheusadapter.New(prometheus.NewRegistry()))
    43  	ctx = tracer.CtxWithTracer(ctx, zipkin.Default())
    44  	ctx = errmon.CtxWithErrorMonitor(ctx, errmonlogger.New(logger.FromCtx(ctx)))
    45  
    46  	ctx = beltctx.WithTraceID(ctx, belt.RandomTraceID())
    47  	ctx = beltctx.WithField(ctx, "pid", os.Getpid(), metrics.AllowInMetrics)
    48  	ctx = beltctx.WithFields(ctx, &field.Field{Key: "field0", Value: "value0"})
    49  
    50  	go func() {
    51  		errmon.ObserveErrorCtx(ctx, http.ListenAndServe("localhost:6060", nil))
    52  	}()
    53  
    54  	doSomething(ctx)
    55  }
    56  
    57  func doSomething(ctx context.Context) {
    58  	span, ctx := tracer.StartSpanFromCtx(ctx, "doSomething")
    59  	defer span.Finish()
    60  	// prints:
    61  	// 2022/07/06 11:45:53 2022-07-06 11:45:53.513474862 +0100 IST m=+0.010575838:
    62  	// {
    63  	//   "timestamp": 1657104353512656,
    64  	//   "duration": 798,
    65  	//   "traceId": "0bab5ae6fef17cc9",
    66  	//   "id": "0bab5ae6fef17cc9",
    67  	//   "name": "dosomething",
    68  	//   "tags": {
    69  	//     "field0": "value0",
    70  	//     "pid": "1662371",
    71  	//     "trace_ids": "d8cfd7a8-2b28-4b9a-9848-5a4a481cecbf"
    72  	//   }
    73  	// }
    74  
    75  	ctx = beltctx.WithField(ctx, "uid", os.Getuid())
    76  	logger.FromCtx(ctx).Infof("yay!")
    77  	// prints:
    78  	// {"level":"info","ts":1657286934.0679588,"msg":"yay!","uid":1000,"field0":"value0","pid":2446918}
    79  
    80  	logFields(ctx)
    81  	useLogger(beltctx.WithField(ctx, "someField", "someValue"))
    82  	tryChildSpan(ctx)
    83  	tryPanic(ctx)
    84  	observerErr(ctx)
    85  	useMetrics(ctx)
    86  }
    87  
    88  func tryPanic(ctx context.Context) {
    89  	defer func() { errmon.ObserveRecoverCtx(ctx, recover()) }()
    90  	// prints:
    91  	// {"level":"error","ts":1657286934.0684156,"caller":"everything/main.go:77","msg":"got panic with argument: some well-respected reason to panic","uid":1000,"field0":"value0","pid":2446918,"trace_id":["5e4e44ce-272f-4e0f-b66c-6a7dff511ce6"]}
    92  
    93  	panic("some well-respected reason to panic")
    94  }
    95  
    96  func observerErr(ctx context.Context) {
    97  	for _, err := range []error{fmt.Errorf("some error"), nil} {
    98  		errmon.ObserveErrorCtx(ctx, err)
    99  	}
   100  	// prints:
   101  	// {"level":"error","ts":1657286934.068724,"caller":"everything/main.go:86","msg":"some error","uid":1000,"field0":"value0","pid":2446918,"trace_id":["5e4e44ce-272f-4e0f-b66c-6a7dff511ce6"]}
   102  }
   103  
   104  func logFields(ctx context.Context) {
   105  	log := logger.FromCtx(ctx)
   106  
   107  	beltctx.Belt(ctx).Fields().ForEachField(func(f *field.Field) bool {
   108  		log.Debugf("%#+v", *f)
   109  		return true
   110  	})
   111  	// prints:
   112  	// {"level":"debug","ts":1657286934.068012,"msg":"field.Field{Key:\"uid\", Value:1000, Properties:field.Properties(nil)}","uid":1000,"field0":"value0","pid":2446918}
   113  	// {"level":"debug","ts":1657286934.0680254,"msg":"field.Field{Key:\"field0\", Value:\"value0\", Properties:field.Properties(nil)}","uid":1000,"field0":"value0","pid":2446918}
   114  	// {"level":"debug","ts":1657286934.0680408,"msg":"field.Field{Key:\"pid\", Value:2446918, Properties:field.Properties{types.fieldPropertyAllowInMetricsT{}}}","uid":1000,"field0":"value0","pid":2446918}
   115  }
   116  
   117  func useLogger(ctx context.Context) {
   118  	logger.FromCtx(ctx).InfoFields("Hello here as well!", &field.Field{Key: "custom_field", Value: 123})
   119  	// prints:
   120  	// {"level":"info","ts":1657286934.0680518,"msg":"Hello here as well!","uid":1000,"field0":"value0","pid":2446918,"someField":"someValue","custom_field":123}
   121  }
   122  
   123  func tryChildSpan(ctx context.Context) {
   124  	span, ctx := tracer.StartChildSpanFromCtx(ctx, "tryChildSpan")
   125  	defer span.Finish()
   126  	// prints:
   127  	// 2022/07/08 14:28:54 2022-07-08 14:28:54.068304102 +0100 IST m=+0.011247634:
   128  	// {
   129  	//   "timestamp": 1657286934068076,
   130  	//   "duration": 1,
   131  	//   "traceId": "1e832b96d001606b",
   132  	//   "id": "0b8352f99252595c",
   133  	//   "parentId": "1e832b96d001606b",
   134  	//   "name": "trychildspan",
   135  	//   "tags": {
   136  	//     "field0": "value0",
   137  	//     "pid": "2446918",
   138  	//     "trace_ids": "5e4e44ce-272f-4e0f-b66c-6a7dff511ce6",
   139  	//     "uid": "1000"
   140  	//   }
   141  	// }
   142  
   143  	// doing something here
   144  	_ = ctx
   145  }
   146  
   147  func useMetrics(ctx context.Context) {
   148  	defer metrics.FromCtx(ctx).IntGauge("concurrent").Add(1).Add(-1)
   149  	metrics.FromCtx(ctx).Count("total").Add(1)
   150  
   151  	exportMetrics(ctx)
   152  }
   153  
   154  func exportMetrics(ctx context.Context) {
   155  	// exporting metrics is not an implementation-agnostic procedure
   156  	metrics, err := metrics.FromCtx(ctx).(*prometheusadapter.Metrics).Gatherer().Gather()
   157  	errmon.ObserveErrorCtx(ctx, err)
   158  
   159  	var buf bytes.Buffer
   160  	enc := expfmt.NewEncoder(&buf, expfmt.FmtText)
   161  	for _, metric := range metrics {
   162  		if err := enc.Encode(metric); err != nil {
   163  			errmon.ObserveErrorCtx(ctx, err)
   164  			return
   165  		}
   166  	}
   167  
   168  	fmt.Print(buf.String())
   169  	// prints:
   170  	// # HELP concurrent_int
   171  	// # TYPE concurrent_int gauge
   172  	// concurrent_int{pid="2446918"} 1
   173  	// # HELP total_count
   174  	// # TYPE total_count counter
   175  	// total_count{pid="2446918"} 1
   176  }