Jenny Hilton
Jenny Hilton

Reputation: 1407

Use same object instance(log) in diffrent files

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

Upvotes: 1

Views: 1478

Answers (1)

Eddy Hernandez
Eddy Hernandez

Reputation: 5886

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")
}

Upvotes: 4

Related Questions