Golang 微服務系列 go-kit(Log,Metrics,Tracing)

go-kit Log & Metrics & Tracing

微服務監控3大核心 Log & Metrics & Tracing

Log

Log 模塊源碼有待分析(分析完再補上)

Metrics

主要是封裝 Metrics 接口,及各個 Metrics(Prometheus,InfluxDB,StatsD,expvar) 中間件的封裝。

// Counter describes a metric that accumulates values monotonically.
// An example of a counter is the number of received HTTP requests.
type Counter interface {With(labelValues ...string) CounterAdd(delta float64)
}// Gauge describes a metric that takes specific values over time.
// An example of a gauge is the current depth of a job queue.
type Gauge interface {With(labelValues ...string) GaugeSet(value float64)Add(delta float64)
}// Histogram describes a metric that takes repeated observations of the same
// kind of thing, and produces a statistical summary of those observations,
// typically expressed as quantiles or buckets. An example of a histogram is
// HTTP request latencies.
type Histogram interface {With(labelValues ...string) HistogramObserve(value float64)
}

Tracing

Tracing 主要是對 Zipkin, OpenTracing, OpenCensus 的封裝。

Zipkin

func TraceEndpoint(tracer *zipkin.Tracer, name string) endpoint.Middleware {return func(next endpoint.Endpoint) endpoint.Endpoint {return func(ctx context.Context, request interface{}) (interface{}, error) {var sc model.SpanContextif parentSpan := zipkin.SpanFromContext(ctx); parentSpan != nil {sc = parentSpan.Context()}sp := tracer.StartSpan(name, zipkin.Parent(sc))defer sp.Finish()ctx = zipkin.NewContext(ctx, sp)return next(ctx, request)}}
}

OpenTracing

// TraceServer returns a Middleware that wraps the `next` Endpoint in an
// OpenTracing Span called `operationName`.
//
// If `ctx` already has a Span, it is re-used and the operation name is
// overwritten. If `ctx` does not yet have a Span, one is created here.
func TraceServer(tracer opentracing.Tracer, operationName string) endpoint.Middleware {return func(next endpoint.Endpoint) endpoint.Endpoint {return func(ctx context.Context, request interface{}) (interface{}, error) {serverSpan := opentracing.SpanFromContext(ctx)if serverSpan == nil {// All we can do is create a new root span.serverSpan = tracer.StartSpan(operationName)} else {serverSpan.SetOperationName(operationName)}defer serverSpan.Finish()otext.SpanKindRPCServer.Set(serverSpan)ctx = opentracing.ContextWithSpan(ctx, serverSpan)return next(ctx, request)}}
}// TraceClient returns a Middleware that wraps the `next` Endpoint in an
// OpenTracing Span called `operationName`.
func TraceClient(tracer opentracing.Tracer, operationName string) endpoint.Middleware {return func(next endpoint.Endpoint) endpoint.Endpoint {return func(ctx context.Context, request interface{}) (interface{}, error) {var clientSpan opentracing.Spanif parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {clientSpan = tracer.StartSpan(operationName,opentracing.ChildOf(parentSpan.Context()),)} else {clientSpan = tracer.StartSpan(operationName)}defer clientSpan.Finish()otext.SpanKindRPCClient.Set(clientSpan)ctx = opentracing.ContextWithSpan(ctx, clientSpan)return next(ctx, request)}}
}

OpenCensus

func TraceEndpoint(name string, options ...EndpointOption) endpoint.Middleware {if name == "" {name = TraceEndpointDefaultName}cfg := &EndpointOptions{}for _, o := range options {o(cfg)}return func(next endpoint.Endpoint) endpoint.Endpoint {return func(ctx context.Context, request interface{}) (response interface{}, err error) {ctx, span := trace.StartSpan(ctx, name)if len(cfg.Attributes) > 0 {span.AddAttributes(cfg.Attributes...)}defer span.End()defer func() {if err != nil {if lberr, ok := err.(lb.RetryError); ok {// handle errors originating from lb.Retryattrs := make([]trace.Attribute, 0, len(lberr.RawErrors))for idx, rawErr := range lberr.RawErrors {attrs = append(attrs, trace.StringAttribute("gokit.retry.error."+strconv.Itoa(idx+1), rawErr.Error(),))}span.AddAttributes(attrs...)span.SetStatus(trace.Status{Code:    trace.StatusCodeUnknown,Message: lberr.Final.Error(),})return}// generic errorspan.SetStatus(trace.Status{Code:    trace.StatusCodeUnknown,Message: err.Error(),})return}// test for business errorif res, ok := response.(endpoint.Failer); ok && res.Failed() != nil {span.AddAttributes(trace.StringAttribute("gokit.business.error", res.Failed().Error()),)if cfg.IgnoreBusinessError {span.SetStatus(trace.Status{Code: trace.StatusCodeOK})return}// treating business error as real error in span.span.SetStatus(trace.Status{Code:    trace.StatusCodeUnknown,Message: res.Failed().Error(),})return}// no errors identifiedspan.SetStatus(trace.Status{Code: trace.StatusCodeOK})}()response, err = next(ctx, request)return}}
}

使用

參考 examples/set.go

var concatEndpoint endpoint.EndpointconcatEndpoint = MakeConcatEndpoint(svc)
concatEndpoint = opentracing.TraceServer(otTracer, "Concat")(concatEndpoint)
concatEndpoint = zipkin.TraceEndpoint(zipkinTracer, "Concat")(concatEndpoint)
concatEndpoint = LoggingMiddleware(log.With(logger, "method", "Concat"))(concatEndpoint)
concatEndpoint = InstrumentingMiddleware(duration.With("method", "Concat"))(concatEndpoint)

小結

通過把第三方中間件封裝成 endpoint.Middleware, 可以與其它 go-kit 中間件組合。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/276561.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/276561.shtml
英文地址,請注明出處:http://en.pswp.cn/news/276561.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

GDI+

載解壓GDI開發包&#xff1b; 2&#xff0e; 正確設置include & lib 目錄&#xff1b; 3&#xff0e; stdafx.h 添加&#xff1a; #ifndef ULONG_PTR #define ULONG_PTR unsigned long* #endif #include <gdiplus.h> 4&#xff0e; 程序中添加GDI的包含文件gdip…

shell 練習3

1、編寫腳本/root/bin/createuser.sh&#xff0c;實現如下功能&#xff1a;使用一個用戶名做為參數&#xff0c;如果指定參數的用戶存在&#xff0c;就顯示其存在&#xff0c;否則添加之&#xff1b;顯示添加的用戶的id號等信息2、編寫腳本/root/bin/yesorno.sh&#xff0c;提示…

HTML5文件實現拖拽上傳

轉載鏈接&#xff1a;http://www.cnblogs.com/caonidayecnblogs/archive/2010/09/09/1821925.html 通過HTML的文件API &#xff0c;Firefox、Chrome等瀏覽器已經支持從操作系統直接拖拽文件&#xff0c;并上傳到服務器。 相對于使用了十多年的HTML表單&#xff0c;這是一個革命…

兩個數組結果相減_學點算法(三)——數組歸并排序

今天來學習歸并排序算法。分而治之歸并算法的核心思想是分而治之&#xff0c;就是將大問題轉化為小問題&#xff0c;在解決小問題的基礎上&#xff0c;再去解決大問題。將這句話套用到排序中&#xff0c;就是將一個大的待排序區間分為小的待排序區間&#xff0c;對小的排序區間…

python實習生面試題_大數據分析實習生面試題庫

原標題&#xff1a;大數據分析實習生面試題庫大數據分析是一個有吸引力的領域&#xff0c;因為它不僅有利可圖&#xff0c;而且您有機會從事有趣的項目&#xff0c;而且您總是在學習新事物。如果您想從頭開始&#xff0c;請查看大數據分析實習生面試題庫以準備面試要點。大數據…

JavaScript編程語言 基礎 (1)

問題&#xff1a;什么是web前端前端&#xff1a;指界面&#xff0c;計算機&#xff08;PC&#xff09;軟件桌面的界面&#xff1b; 計算機端的瀏覽器界面&#xff1b; 移動端的軟件&#xff08;app&#xff09;界面&#xff1b; 移動端的瀏覽器界面。HtmlcssJavaScript 使用網頁…

shell結合expect寫的批量scp腳本工具

轉載鏈接&#xff1a;http://www.jb51.net/article/34005.htm expect用于自動化地執行linux環境下的命令行交互任務&#xff0c;例如scp、ssh之類需要用戶手動輸入密碼然后確認的任務。有了這個工具&#xff0c;定義在scp過程中可能遇到的情況&#xff0c;然后編寫相應的處理語…

ASP記數器

這兩天有好幾個老的ASP網站要改&#xff0c;其中有要求加記數器&#xff0c;為圖簡單&#xff0c;就用文本文件的形式存儲記數。以前用ifream的形式嵌入&#xff0c;不能很好的控制記數器顯示的風格&#xff0c;現在改進了一下&#xff0c;可以很好的與嵌入板塊風格結合了。把做…

php利用openssl實現RSA非對稱加密簽名

轉載鏈接&#xff1a;http://liuxufei.com/weblog/jishu/376.html 1. 先用php生成一對公鑰和私鑰 $res openssl_pkey_new(); openssl_pkey_export($res,$pri); $d openssl_pkey_get_details($res); $pub $d[key]; var_dump($pri,$pub); 2. 保存好自己的私鑰&#xff0c;把公…

[轉] DevExpress 第三方控件漢化的全部代碼和使用方法

DevExpress.XtraEditors.Controls 此控件包中包含的控件最多&#xff0c;包括文本框&#xff0c;下拉列表&#xff0c;按鈕&#xff0c;等等 DevExpress.XtraGrid 網格 DevExpress.XtraBars 菜單欄 和 工具欄 DevExpress.XtraNavBar 導航條 DevExpress.XtraPr…

QPM 性能監控組件總篇

QPM &#xff08;Quality Performance Monitor&#xff09; 是一個質量性能監控組件&#xff0c;可以很方便的查看當前 App 的性能和常用數據。目前主要運行在 Android 平臺上&#xff0c;通過集成 QPM 組件&#xff0c;可以在 App 中通過懸浮窗可視化相關實時數據。意在幫助廣…

福音!微信個人公眾號可以改名了!

微信個人公眾號可以改名了&#xff01;&#xff01;&#xff01;今年&#xff0c;我們學校從景德鎮陶瓷學院更名為景德鎮陶瓷大學&#xff0c;但苦于微信限制&#xff0c;很多微信公眾號無法更名。很多組織社團就放棄了原先的關注量&#xff0c;重新申請注冊賬號。當前我們的訂…

js list刪除指定元素_刪除js數組中的指定元素,有這兩步就夠了

js數組是js部分非常重要的知識&#xff0c;有時我們有這么個需求js數組刪除指定元素&#xff0c;先定義一個函數來獲取刪除指定元素索引值&#xff0c;然后用js數組刪除的方法&#xff0c;來刪除指定元素即可&#xff0c;就兩步不難&#xff0c;很簡單。1、JS的數組對象定義一個…

sudo 安裝 常見錯誤

運行環境Linux&#xff1a; 1、sudo&#xff1a;安裝 apt-get install sudo 2、sudo: must be setuid root錯誤解決方法. ls -l /usr/bin/sudo chown root:root /usr/bin/sudo chmod 4755 /usr/bin/sudo reboot 3、sudo&#xff1a;提示用戶無權限之類 在 /etc/…

慕課網高并發實戰(一)-并發與高并發基本概念

課程網址 并發&#xff1a; 同時擁有兩個或者多個線程&#xff0c;如果程序在單核處理器上運行&#xff0c;多個線程交替得換入或者換出內存&#xff0c;這些線程是同時“存在”的&#xff0c;每個線程都處于執行過程中的某個狀態&#xff0c;如果運行在多核處理器上&#xff…

2009最經典名句

一&#xff1a;我的優點是&#xff1a;我很帥&#xff1b;但是我的缺點是&#xff1a;我帥的不明顯. 二&#xff1a;談錢不傷感情&#xff0c;談感情最他媽傷錢。 三&#xff1a;我詛咒你一輩子買方便面沒有調料包。 四&#xff1a;會計說&#xff1a;“你晚點來領工資吧&#…

計算機協會丨讓技能得到提升,讓思維受到啟迪

“ 各位2016級新生&#xff0c;新的學期馬上就要開始了&#xff0c;學校的各個組織和社團你真的了解了嗎&#xff1f;在眼花繚亂的社團里如何找到自己真正喜歡的呢&#xff1f;或許看完計算機協會的納新微信你就都明白啦&#xff01;關鍵詞&#xff1a;計算機協會景德鎮陶瓷大學…

ondestroy什么時候調用_尾調用和尾遞歸

尾調用1. 定義尾調用是函數式編程中一個很重要的概念&#xff0c;當一個函數執行時的最后一個步驟是返回另一個函數的調用&#xff0c;這就叫做尾調用。注意這里函數的調用方式是無所謂的&#xff0c;以下方式均可&#xff1a;函數調用: func()方法調用: obj.method()call調用:…

查看/修改Linux時區和時間

轉載鏈接&#xff1a;http://blog.csdn.net/colincjl/article/details/6133036 查看/修改Linux時區和時間 一、時區 1. 查看當前時區 date -R 2. 修改設置時區 方法(1) tzselect 方法(2) 僅限于RedHat Linux 和 CentOS timeconfig 方法(3) 適用于Debian dpkg-reconfigure tzdat…

dhl:使用return RedirectToAction()和 return view()

一個Action&#xff1a; Code/// <summary> /// Friend好友的地 /// </summary> /// <returns></returns> public ActionResult FriendFarm(string pid) {BLL.DTOFarm farm new AppleGrange.BLL.DTOFarm(pid); …