英文:
Package dependencies and initialization
问题
我是新手学习Go语言,正在尝试解决以下问题。
- 目标是将所有日志写入文件。
- 主包导入了包A。
- 在主包的main方法中,设置了日志写入文件的配置。
- 包A中有一个init函数,在A的init函数中有一行日志 - log.Fatal("I am package A")。
- 由于主包导入了A,A的init函数会首先被调用(甚至在我们设置日志写入文件的配置之前)。
如何解决这个问题,使得日志"I am package A"被写入文件中?
英文:
I'm new to Go and trying to find a solution to the following problem.
- The goal is to write all logs to a file.
- package main imports package A.
- In package main, in the main method, logging is setup to write to a file
- package A has an init function. In the init function of A, there is a log line - log.Fatal("I am package A").
- 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?
答案1
得分: 3
将日志初始化移出到一个名为log
的包中,该包被main
和A
两个模块导入,并且在初始化过程中不直接或间接依赖于你想要记录到文件的应用程序的其他部分。根据Effective Go和规范中的初始化顺序描述,这样就足以确保日志在最开始初始化。
英文:
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.
答案2
得分: 0
如果包A的init函数依赖于其他操作完成,那么唯一可以放置这些操作的地方就是A所依赖的包的init函数中。如果你想要对这些操作进行参数化,你需要将所有内容从init
函数中移出,并放入手动调用的函数中(比如CustomInit
),这样你就可以控制调用顺序、参数等。
基本上,你不能有带参数的init函数。由于A的init函数记录到一个带参数的日志对象中,这使得它(间接地)带有参数,所以你不能使用内置的init
函数来实现这个目的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论