github.com/braveheart12/just@v0.8.7/ledger/artifactmanager/instrument.go (about)

     1  /*
     2   *    Copyright 2019 Insolar Technologies
     3   *
     4   *    Licensed under the Apache License, Version 2.0 (the "License");
     5   *    you may not use this file except in compliance with the License.
     6   *    You may obtain a copy of the License at
     7   *
     8   *        http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   *    Unless required by applicable law or agreed to in writing, software
    11   *    distributed under the License is distributed on an "AS IS" BASIS,
    12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   *    See the License for the specific language governing permissions and
    14   *    limitations under the License.
    15   */
    16  
    17  package artifactmanager
    18  
    19  import (
    20  	"context"
    21  	"time"
    22  
    23  	"go.opencensus.io/stats"
    24  	"go.opencensus.io/tag"
    25  
    26  	"github.com/insolar/insolar/instrumentation/inslogger"
    27  	"github.com/insolar/insolar/instrumentation/insmetrics"
    28  )
    29  
    30  type methodInstrumenter struct {
    31  	ctx     context.Context
    32  	name    string
    33  	start   time.Time
    34  	errlink *error
    35  }
    36  
    37  func instrument(ctx context.Context, name string) *methodInstrumenter {
    38  	return &methodInstrumenter{
    39  		ctx:   ctx,
    40  		start: time.Now(),
    41  		name:  name,
    42  	}
    43  }
    44  
    45  func (mi *methodInstrumenter) err(err *error) *methodInstrumenter {
    46  	mi.errlink = err
    47  	return mi
    48  }
    49  
    50  func (mi *methodInstrumenter) end() {
    51  	latency := time.Since(mi.start)
    52  	inslog := inslogger.FromContext(mi.ctx)
    53  
    54  	code := "2xx"
    55  	if mi.errlink != nil && *mi.errlink != nil {
    56  		code = "5xx"
    57  		inslog.Error(*mi.errlink)
    58  	}
    59  
    60  	ctx := insmetrics.InsertTag(mi.ctx, tagMethod, mi.name)
    61  	ctx = insmetrics.ChangeTags(
    62  		ctx,
    63  		tag.Insert(tagMethod, mi.name),
    64  		tag.Insert(tagResult, code),
    65  	)
    66  	stats.Record(ctx, statCalls.M(1), statLatency.M(latency.Nanoseconds()/1e6))
    67  }