亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 包中正確的日志記錄實現

Golang 包中正確的日志記錄實現

Go
慕桂英546537 2022-06-13 16:55:06
我有一個小的 Golang包,它可以做一些工作。這項工作假設可能會產生大量錯誤,這是可以的。目前所有錯誤都被忽略。是的,它可能看起來很奇怪,但請訪問鏈接并檢查包的主要用途。我想擴展包的功能并提供在運行時查看錯誤的能力。但是由于缺乏軟件設計技能,我有一些問題沒有答案。起初,我想使用現有的日志記錄(zerolog、zap 或其他任何東西)在包內實現日志記錄。但是,包的用戶可以嗎?因為他們可能想使用其他日志記錄包并想修改輸出格式。也許有可能為用戶提供一種注入它自己的日志記錄的方法?我想實現提供易于配置的日志記錄方式的能力,可以根據用戶的需求打開或關閉。
查看完整描述

2 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

有些 go lib 使用這樣的日志記錄


在你的包中確定一個記錄器接口


type Yourlogging interface{

      Errorf(...)

      Warningf(...)

      Infof(...)

      Debugf(...)

}

并為此接口定義一個變量


  var mylogger Yourlogging

  func SetLogger(l yourlogging)error{

       mylogger = l

  }

在您的函數中,您可以調用它們進行日志記錄


  mylogger.Infof(..)


  mylogger.Errorf(...)

你不需要實現接口,但是你可以使用實現這個接口的他們


 for example:

     SetLogger(os.Stdout)    //logging output to stdout

     SetLogger(logrus.New()) // logging output to logrus  (github.com/sirupsen/logrus)

  

查看完整回答
反對 回復 2022-06-13
?
MM們

TA貢獻1886條經驗 獲得超2個贊

在 Go 中,您會看到一些庫實現了日志接口,就像其他答案所建議的那樣。但是,例如,如果您以不同的方式構建應用程序,則可以完全避免您的包需要記錄。


例如,在您鏈接的示例應用程序中,您的主應用程序運行時調用idleexacts.Run(),它會啟動此函數。


// startLoop starts workload using passed settings and database connection.

func startLoop(ctx context.Context, log log.Logger, pool db.DB, tables []string, jobs uint16, minTime, maxTime time.Duration) error {

    rand.Seed(time.Now().UnixNano())


    // Increment maxTime up to 1 due to rand.Int63n() never return max value.

    maxTime++


    // While running, keep required number of workers using channel.

    // Run new workers only until there is any free slot.

    guard := make(chan struct{}, jobs)

    for {

        select {

        // Run workers only when it's possible to write into channel (channel is limited by number of jobs).

        case guard <- struct{}{}:

            go func() {

                table := selectRandomTable(tables)

                naptime := time.Duration(rand.Int63n(maxTime.Nanoseconds()-minTime.Nanoseconds()) + minTime.Nanoseconds())


                err := startSingleIdleXact(ctx, pool, table, naptime)

                if err != nil {

                    log.Warnf("start idle xact failed: %s", err)

                }


                // When worker finishes, read from the channel to allow starting another worker.

                <-guard

            }()

        case <-ctx.Done():


            return nil

        }

    }

}

這里的問題是你的邏輯的所有編排都發生在你的包內部。相反,這個循環應該在你的主應用程序中運行,并且這個包應該為用戶提供簡單的操作,例如selectRandomTable()or createTempTable()。


如果代碼編排在您的主應用程序中,并且包僅提供簡單的操作。作為函數調用的一部分,將錯誤返回給用戶會容易得多。


它還可以使您的包更容易被其他人重用,因為它們具有簡單的操作并且可以讓用戶以超出您預期的其他方式使用它們。


查看完整回答
反對 回復 2022-06-13
  • 2 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號