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条)

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划