Question

I'm new to Go and trying to find a solution to the following problem.

  1. The goal is to write all logs to a file.
  2. package main imports package A.
  3. In package main, in the main method, logging is setup to write to a file
  4. package A has an init function. In the init function of A, there is a log line - log.Fatal("I am package A").
  5. Since main package imports A, A's init function is first called (even before we get a chance to setup the logs to write to a file).

How to resolve this so the log "I am package A" gets written to a file?

Was it helpful?

Solution

Move logging initialization out to a log package that is imported by both main and A and does not depend directly or indirectly on the parts of your app that you want to log to the file during initialization. From the descriptions of init order in Effective Go and the spec, that should be enough to make sure your logging is initialized first thing.

OTHER TIPS

If the init function of package A depends on something else being done, the only place in which that something else can be put is in the init function of a package depended on by A. If you want to be able to parametrize that something else, you need to move everything out of init and into manually-called functions (call them CustomInit or something) for which you can control the call order, parameters, etc.

Basically, you can't have parametrized init functions. Since A's init function logs to a parametrized logging object, that makes it (indirectly) parametrized, so you can't use the built-in init function for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top