0

I have developed a custom logging package in Go, which I'll refer to as customLogger, providing logging capabilities with different log levels (Debug, Info, Warning, and Error). This package encapsulates the functionality of the standard log.Logger and also includes additional details such as function name, filename, and line number when logging.

To use this logging package in my Go project, I currently need to import it with the following import statement:

import customLogger "logger/customLogger"

After importing, I can log messages using the package as follows:

customLogger.Logging().Debug("Custom debug message")
customLogger.Logging().Info("Custom info message")
customLogger.Logging().Error("Custom error message")

However, I would like to simplify the usage of this package by making the logger globally accessible without revealing its source code. My goal is to use it like this:

Logging().Debug("Custom debug message")
Logging().Info("Custom info message")
Logging().Error("Custom error message")

Is there a way to modify the customLogger package to create a global instance of the logger, enabling me to use the logger functions directly, without importing the package in every file where I want to log messages?

Thank you for your expertise and suggestions!

Jocefyneroot
  • 137
  • 1
  • 11

1 Answers1

0

No, what you can do however is get rid of calling Logging() everytime.

Add some wrapper functions inside the customLogger package, where you basically wrap it. This way you could call customlogger.Error(message)

(It is generally recommended to keep package names lowercase)

Example:

package customlogger

... 

func Error(args ...any) {
    globallyDefinedLogger.Error(args...)
}
nigel239
  • 1,485
  • 1
  • 3
  • 23
  • I'm asking for a way to create a global instance of the logger, enabling me to use the logger functions directly, without importing the package in every file where I want to log messages. – Jocefyneroot Jul 25 '23 at 09:57
  • This is the best you're going to get. You will need to import it in every file you use it. Why is this a requirement for you? – nigel239 Jul 25 '23 at 10:56
  • 1
    You can write a [dot import](https://stackoverflow.com/questions/6478962) if you don't want to mention the package name. You cannot use your library without any import statement. – Peter Jul 25 '23 at 17:42
  • @Peter okay, thanks for your feedback, I'll definitely be going to think about it but I've to implement this feature in the code base, if there is any way to archive this then let me know otherwise no problem, thank you. – Jocefyneroot Jul 26 '23 at 07:24