英文:
How to separate logs from different packages
问题
我正在努力找出如何将来自不同软件包的日志分开的方法。
示例:
package main
import (
"log"
"github.com/org/verbose"
)
func main() {
log.Print("Hello World")
verbose.DoSomething() // 这将生成大量日志消息
}
我知道有一个标志log.Llongfile
,我可以启用它,然后日志中的每一行都包含日志消息来自的文件的完整路径。然而,这仍然意味着我需要进行一些后处理,从单个文件中过滤出我不想要的内容和我想要的内容。
我希望能够实时进行过滤,这样我最终会得到verbose-lib.log
和my-app.log
之类的日志文件。
我正在寻找一个适用于大多数现有开源软件包的解决方案 - 也就是说,我不能随意更改这些库中的日志记录机制,因此我认为自定义日志记录库不适用。
英文:
I'm struggling to find out how to separate logs coming from different packages.
Example:
package main
import (
"log"
"github.com/org/verbose"
)
func main() {
log.Print("Hello World")
verbose.DoSomething() // Which will generate a lot log messages
}
I know there's flag log.Llongfile
which I can enable and then each line inside the log will contain the full path of the file where is the log message coming from. This however still means I'll need to do some post-processing to filter out from that single file what I don't want and what I do want.
I'd like to do that filtering in real-time already, so I end up having verbose-lib.log
and my-app.log
or something like that.
I'm looking for a solution that will work with most existing OSS packages - i.e. I cannot just change logging mechanisms in these libraries in any way I want, hence custom logging libraries are out of the game I reckon.
答案1
得分: 2
如果包将其记录器暴露给您,您可以为其创建一个带有前缀的新记录器:
package main
import (
"log"
"os"
"example.com/lib/foo"
)
func main() {
foo.Logger := log.New(os.Stderr, "libfoo: ", log.LstdFlags)
// 做一些操作。
}
这样,foo
的消息将会是这样的:
libfoo: 2015/09/14 17:04:52 Something's happened!
另外,log.New
接受一个io.Writer
参数,因此您可以打开任何文件并直接将日志写入其中。
英文:
If the package exposes its logger to you, you can create a new logger for it with a prefix:
package main
import (
"log"
"os"
"example.com/lib/foo"
)
func main() {
foo.Logger := log.New(os.Stderr, "libfoo: ", log.LstdFlags)
// Do stuff.
}
This way, foo
's messages will look like this:
libfoo: 2015/09/14 17:04:52 Something's happened!
Additionally, log.New
accepts an io.Writer
, so you can open any file and make it just write there directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论