Golang日志多态性?

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

Golang Logger polymorphism?

问题

我们使用一个第三方库,该库在其New函数中接受*log.Logger(stdlib Logger)作为参数,但我们自己实现了Logger。它与stdlib Logger具有相同的“接口”。

除了要求库的所有者更改参数类型为接口之外,是否有任何方法可以将我们自己实现的Logger传递给第三方库?

英文:

We use a third party library which accepts *log.Logger (stdlib Logger) as a parameter in its New function, but we implement Logger by ourself. It has the same "interface" with stdlib Logger.

Is there any hack way to pass our own implementation of Logger to the third library excepting asking the library owner to change the parameter type to interface?

答案1

得分: 1

如果他们的包使用了一个实际的*log.Logger,除了将log.Logger的输出设置为自定义的写入器,拦截他们的日志语句并通过你自己的日志记录它们之外,你无法注入自己的日志记录器。

但这样做可能不太理想,因为你基本上需要解析他们的所有日志语句,只为了重新记录它们。不确定log.Logger是否将日志消息作为一次调用Write来写入。如果是这样的话,只需在每次调用Write时重新记录即可。

你可能还想考虑找到另一个库,或者分叉并更改该库,因为没有什么东西真的应该依赖于log.Logger。

英文:

If their package takes an actual *log.Logger, there's nothing you can do to inject your own logger other than set the output of a log.Logger to a custom writer where you intercept their log statements and you then re-log them through yours.

But that will be sub-awesome as you'd basically be parsing all their log statements just so you can re-log. Not sure if log.Logger writes a log message as one call to Write. if it does, it's easy as all you do is re-log for every call to Write.

You might also want to consider finding another library or forking and changing that library as nothing should really depend on log.Logger like that.

huangapple
  • 本文由 发表于 2016年4月10日 12:22:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/36525757.html
匿名

发表评论

匿名网友

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

确定