如何将日志从单独的程序包写入单独的文件

Here, I have an app which has multiple packages underneath and I don't want to write the logs into one file. Say for eg:

   src/packageA/snmp.go
   src/packageA/http.go

I want to write the logs from snmp.go to /var/log/snmp.log and http.go to /var/log/http.log

James

runtime.Caller(0) should get you this information. For example:

package main

import (
    "fmt"
    "runtime"
    "path"
    "path/filepath"
)

func main() {
    _, filename, _, ok := runtime.Caller(0)
    if !ok {
        panic("No caller!")
    }
    fmt.Printf("Calling file: %s
", path.Base(filename))

    // Without extension
    fname := fmt.Sprintf("%s.log", path.Base(filename[0:len(filename)-len(filepath.Ext(filename))]))
    fmt.Printf("Desired log file name: %s
", fname)

    // you can now use fname to form desired log path
    logPath := path.Join("/var/log", fname)
    fmt.Printf("Desired log path: %s
", logPath)
}

This example will output:

Calling file: main.go
Desired log file name: main.log
Desired log path: /var/log/main.log

This is just an example. Try experimenting with a different integer parameter to runtime.Caller() if this doesn't work.

If you use logrus it might be useful https://github.com/rifflock/lfshook