doukuanjing5404 2016-03-21 17:54
浏览 51
已采纳

如何根据golang中的“调用者”程序创建一个包以使用任何记录器?

As I can see, each developer has its own need and approach to solve same things/needs. As an example, logging. There are many logging packages that works in different ways and each developer choose the one that best fits their needs/preferences. Thinking on that, I would like to create a package that should use the caller's logging package. Is it possible? Someone have a way to do that?

Something like this:

Main code using logrus package:

package main

import (
    "os"

    "github.com/Sirupsen/logrus"

    "gitlab.com/tutume/_testing/globallogs/mypack"
)

var Log = logrus.New()

var myPack pack.Pack

func main() {
    isDebug := os.Getenv("MYAPP_LOGLEVEL")
    switch isDebug {
    case "Debug":
        Log.Level = logrus.DebugLevel
    case "Info":
        Log.Level = logrus.InfoLevel
    default:
        Log.Level = logrus.ErrorLevel
    }
    Log.Formatter = &logrus.TextFormatter{
        ForceColors: true,
    }

    Log.Debug("Debugging...")
    Log.Info("Informing...")
    Log.Error("Normal...")

    myPack.Logger = Log
    myPack.DoSomething()

}

mypack code:

package pack

type Pack struct {
    Logger interface{}
}

func (mp *Pack) DoSomething() {
    //  Logger.Debug("Debugging...")
    //  Logger.Info("Informing...")
    //  Logger.Error("Normal...")
}
  • 写回答

2条回答 默认 最新

  • duannue2455 2016-03-22 03:40
    关注

    If I understand what you're trying to do, you need to define an interface that a logging package would implement. If you define Logger as an empty interface, you won't be able to call any of those methods. Instead, you need to define an interface that contains the methods you want to use (Debug, Info, Error, etc.). Any logging package would then have to implement those methods. If a particular logging package doesn't have the right set of methods already, you would have to write some wrapper code to implement the interface as you define it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测