douhuo1738 2017-12-06 13:09
浏览 68
已采纳

使用相同的对象实例(登录不同的文件)

I use logrus logger and I init it inside my main function like following

main.go file content


import "github.com/sirupsen/logrus"

var logger                *logrus.Logger

func init() {

    logger = utils.InitLogs()
}



func main(){

    logger.Info("bla bla")

   } 

And I was able to use it e.g.logger.info(“test”) in the main file, now I don’t want to create the init file in each other file which need to use the logger , I want to use in other project file the same instance which I’ve created in the main.go file How should I do it in golfing ?

Im not asking about sharing it on the same package

  • 写回答

1条回答 默认 最新

  • dongtu0363 2017-12-06 15:21
    关注

    There are some points here:

    Go groups files in package concept for example if you have some .go files in a directory with the package main that means that all files are sharing the package scope, in this case the func init() inits the var logger that is present in the main package.

    I prefer to not use package scope variables, but this depends on your implementation https://dave.cheney.net/2017/06/11/go-without-package-scoped-variables

    Maybe you wanted to use logger in different package for example github.com/youruser/work

    I prefer to pass the object log to the functions or methods you wanted to use it (as parameters or receiver)

    package main
    
    import (
        "github.com/user/utils"
        "github.com/user/work"
    )
    
    func main() {
        logger := utils.InitLogs()
        work.Do(logger)
    }
    

    or using as receiver

    package main
    
    import (
        "github.com/user/utils"
        "github.com/user/work"
    )
    
    func main() {
        logger := utils.InitLogs()
        w := work.New()
        w.Log = logger
        w.Do()
    }
    

    then in Do() you can log using the receiver

    in the work package you should add it as filed

    type Worker struct {
        Log *logrus.Logger
    }
    

    I really hope you can find it useful.

    update: An example of work package

    package work
    
    import "github.com/sirupsen/logrus"
    
    type Worker struct {
        Log *logrus.Logger
    }
    
    func New() *Worker {
        return new(Worker)
    }
    
    func (w *Worker) Do() {
        // some work
        // Here you are passing as receiver parameter
        w.Log.Info("bla bla")
    }
    
    func AnotherFunc(log *logrus.Logger) {
        // Here you are passing as method parameter
       log.Info("bla bla")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题