donglianjiang9321 2018-10-19 20:32 采纳率: 0%
浏览 74
已采纳

在多包中使用logger / configs的最佳做法可提高Golang的生产力

I've the following project structure:

myGithubProject/
    |---- cmd
      |----- command
        |----- hello.go
    |---- internal
        |----- template
           |----- template.go
        |----- log
          |----- logger.go
    main.go

The log and the template are on the same level (under internal package) In logger.go Im using logrus as logger with some config sand I want to use the logger.go object inside the template package. How should I do that in a clean way ?

Currently I use it with import logger inside my template.go file,

And under internal package I’ve 6 more packages which needs this logger. and each of them is depend on it. (On the log package), is there a nice in go to handle it ?

update:

in case I've more things that I need to pass (like logger) what will be the approach/ pattern here ? maybe using dependency injection ? interface ? other clean approach...

I need some best practice full example how can I use logger inside the hello.go file and also in template.go.

this is my project

cliProject/main.go

package main

import (
    "cliProject/cmd"
    "cliProject/internal/logs"
)

func main() {
    cmd.Execute()
    logs.Logger.Error("starting")
}


**cliProject/cmd/root.go**

package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use:   "cliProject",
    Short: "A brief description of your application",
}

func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Println(err)
    }
}

**cliProject/cmd/serve.go**

package cmd

import (
    "cliProject/internal/logs"
    "fmt"

    "github.com/spf13/cobra"
)

// serveCmd represents the serve command
var serveCmd = &cobra.Command{
    Use:   "serve",
    Short: "A brief description of your command",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("serve called")
        startServe()
        stoppingServe()
    },
}

func init() {
    rootCmd.AddCommand(serveCmd)
    serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func startServe() {
    logs.Logger.Error("starting from function serve")
}

func stoppingServe() {
    logs.Logger.Error("stoping from function serve")
}


**cliProject/cmd/start.go**

package cmd

import (
    "cliProject/internal/logs"
    "github.com/spf13/cobra"
)

// startCmd represents the start command
var startCmd = &cobra.Command{
    Use:   "start",
    Short: "Start command",
    Run: func(cmd *cobra.Command, args []string) {
        // Print the logs via logger from internal
        logs.Logger.Println("start called inline")
        // example of many functions which should use the logs...
        start()
        stopping()

    },
}

func init() {
    logs.NewLogger()
    rootCmd.AddCommand(startCmd)
    startCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func start() {
    logs.Logger.Error("starting from function start")
}

func stopping() {
    logs.Logger.Error("stoping from function start")
}


**cliProject/internal/logs/logger.go**

package logs

import (
    "github.com/sirupsen/logrus"
    "github.com/x-cray/logrus-prefixed-formatter"
    "os"
)

var Logger *logrus.Logger

func NewLogger() *logrus.Logger {

    var level logrus.Level
    level = LogLevel("info")
    logger := &logrus.Logger{
        Out:   os.Stdout,
        Level: level,
        Formatter: &prefixed.TextFormatter{
            DisableColors:   true,
            TimestampFormat: "2009-06-03 11:04:075",
        },
    }
    Logger = logger
    return Logger
}

func LogLevel(lvl string) logrus.Level {
    switch lvl {
    case "info":
        return logrus.InfoLevel
    case "error":
        return logrus.ErrorLevel
    default:
        panic("Not supported")
    }
}

this is how it looks

enter image description here

  • 写回答

3条回答 默认 最新

  • dqoys62082 2018-10-22 07:03
    关注

    And under internal package I’ve 6 more packages which needs this logger. and each of them is depend on it. (On the log package), is there a nice in go to handle it ?

    A good general principle would be to respect the application's choice (whether to log or not) instead of setting policy.

    1. Let Go pkgs in your internal directory be support packages that

      • will only return error in case of problems
      • won't log (console or otherwise)
      • won't panic
    2. Let your application (packages in your cmd directory) decide what the appropriate behavior in case of an error (log / graceful shutdown / recover to 100% integrity)

    This would streamline development by having logging at a particular layer only. Note: remember to give the application give enough context to determine action

    internal/process/process.go

    package process
    
    import (
        "errors"
    )
    
    var (
        ErrNotFound = errors.New("Not Found")
        ErrConnFail = errors.New("Connection Failed")
    )
    
    // function Process is a dummy function that returns error for certain arguments received
    func Process(i int) error {
        switch i {
        case 6:
            return ErrNotFound
        case 7:
            return ErrConnFail
        default:
            return nil
        }
    }
    

    cmd/servi/main.go

    package main
    
    import (
        "log"
    
        p "../../internal/process"
    )
    
    func main() {
        // sample: generic logging on any failure
        err := p.Process(6)
        if err != nil {
            log.Println("FAIL", err)
        }
    
        // sample: this application decides how to handle error based on context
        err = p.Process(7)
        if err != nil {
            switch err {
            case p.ErrNotFound:
                log.Println("DOESN'T EXIST. TRY ANOTHER")
            case p.ErrConnFail:
                log.Println("UNABLE TO CONNECT; WILL RETRY LATER")
            }
        }
    }
    

    in case I've more things that I need to pass (like logger) what will be the approach/ pattern here

    Dependency injection is always a good first choice. Consider others only when the simplest implementation is insufficient.

    The code below 'wires' the template and logger packages together using dependency injection and first-class function passing.

    internal/logs/logger.go

    package logger
    
    import (
        "github.com/sirupsen/logrus"
        "github.com/x-cray/logrus-prefixed-formatter"
        "os"
    )
    
    var Logger *logrus.Logger
    
    func NewLogger() *logrus.Logger {
    
        var level logrus.Level
        level = LogLevel("info")
        logger := &logrus.Logger{
            Out:   os.Stdout,
            Level: level,
            Formatter: &prefixed.TextFormatter{
                DisableColors:   true,
                TimestampFormat: "2009-06-03 11:04:075",
            },
        }
        Logger = logger
        return Logger
    }
    
    func LogLevel(lvl string) logrus.Level {
        switch lvl {
        case "info":
            return logrus.InfoLevel
        case "error":
            return logrus.ErrorLevel
        default:
            panic("Not supported")
        }
    }
    

    internal/template/template.go

    package template
    
    import (
        "fmt"
        "github.com/sirupsen/logrus"
    )
    
    type Template struct {
        Name   string
        logger *logrus.Logger
    }
    
    // factory function New accepts a logging function and some data
    func New(logger *logrus.Logger, data string) *Template {
        return &Template{data, logger}
    }
    
    // dummy function DoSomething should do something and log using the given logger
    func (t *Template) DoSomething() {
        t.logger.Info(fmt.Sprintf("%s, %s", t.Name, "did something"))
    }
    

    cmd/servi2/main.go

    package main
    
    import (
        "../../internal/logs"
        "../../internal/template"
    )
    
    func main() {
        // wire our template and logger together
        loggingFunc := logger.NewLogger()
    
        t := template.New(loggingFunc, "Penguin Template")
    
        // use the stuff we've set up
        t.DoSomething()
    }
    

    Hope this helps. Cheers,

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?