包依赖和初始化

huangapple go评论108阅读模式
英文:

Package dependencies and initialization

问题

我是新手学习Go语言,正在尝试解决以下问题。

  1. 目标是将所有日志写入文件。
  2. 主包导入了包A。
  3. 在主包的main方法中,设置了日志写入文件的配置。
  4. 包A中有一个init函数,在A的init函数中有一行日志 - log.Fatal("I am package A")。
  5. 由于主包导入了A,A的init函数会首先被调用(甚至在我们设置日志写入文件的配置之前)。

如何解决这个问题,使得日志"I am package A"被写入文件中?

英文:

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?

答案1

得分: 3

将日志初始化移出到一个名为log的包中,该包被mainA两个模块导入,并且在初始化过程中不直接或间接依赖于你想要记录到文件的应用程序的其他部分。根据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.

huangapple
  • 本文由 发表于 2014年5月10日 07:55:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/23575687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定