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

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟