如何将不同软件包的日志分开?

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

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.logmy-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.

huangapple
  • 本文由 发表于 2015年9月14日 21:59:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/32566740.html
匿名

发表评论

匿名网友

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

确定