如何将日志与其他软件包分开

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.

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.