go-log icon indicating copy to clipboard operation
go-log copied to clipboard

how can we use this logging framework to be available across all the packages in my code

Open AmjadHussainSyed opened this issue 4 years ago • 2 comments

Hi,

how can we use this logging framework to be available across all the packages in my code. something like global logging.

AmjadHussainSyed avatar Jul 14 '20 13:07 AmjadHussainSyed

All the package that you meant is your package only or including third-party library?

You can initiate logger instance using log.New() anywhere. If you want to achieve global logging, I recommend you to follow singleton pattern approach (create an instance of log.Logger then pass it around you code globally)

krsnadjava25 avatar Jul 15 '20 04:07 krsnadjava25

@krsnadjava25 That is not how the Singleton Pattern works. It's not passing that single object around, but the singleton pattern is the way to create once, and reference always. The difference is, if one creates a log instance, and pass it around, another can still be created. You need to prevent creation of another log instance and thus produce a reference to that single log instance every time one is "created" or called.

@AmjadHussainSyed tcheck out https://golangbyexample.com/singleton-design-pattern-go/ ... if it's not too late. My advice would be to wrap a new Struct around logger instance, and use that struct with a singleton pattern.

@AmjadHussainSyed also do this in a package, then import that package where ever you need to use the log instance. This will guarantee the same instance across all your code. That same package you also be used in other projects. Code once, reuse infinite.

skulos avatar Dec 29 '20 12:12 skulos