英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论