From 1617daaf39b3ed0b237fb3b2bf255d9528b0bd97 Mon Sep 17 00:00:00 2001 From: soverdrive Date: Thu, 22 Dec 2016 15:33:49 +0700 Subject: [PATCH] - change Env to EnvKey for clearer init - put option for showing ip address --- example/main.go | 2 +- panics.go | 59 ++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/example/main.go b/example/main.go index 4acded3..e1bc460 100644 --- a/example/main.go +++ b/example/main.go @@ -9,7 +9,7 @@ import ( func main() { panics.SetOptions(&panics.Options{ - Env: "TEST", + EnvKey: "TEST", Filepath: "./", // SlackWebhookURL: "https://hooks.slack.com/services/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", }) diff --git a/panics.go b/panics.go index 1ab7922..0a90785 100644 --- a/panics.go +++ b/panics.go @@ -7,6 +7,7 @@ import ( "fmt" "io/ioutil" "log" + "net" "net/http" "net/http/httputil" "os" @@ -21,6 +22,7 @@ var ( file *os.File env string + ipAddress string filepath string slackWebhookURL string tagString string @@ -29,7 +31,8 @@ var ( type Tags map[string]string type Options struct { - Env string + EnvKey string + ShowIP bool Filepath string SentryDSN string SlackWebhookURL string @@ -40,9 +43,17 @@ func SetOptions(o *Options) { filepath = o.Filepath slackWebhookURL = o.SlackWebhookURL - env = o.Env + env = o.EnvKey var err error + + if o.ShowIP { + ipAddress, err = findMyIP() + if err != nil { + log.Printf("[panics] cannot find IP, %s", err.Error()) + } + } + fp := filepath + "/panics.log" file, err = os.OpenFile(fp, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) if err != nil { @@ -56,10 +67,48 @@ func SetOptions(o *Options) { tagString = strings.Join(tmp, " | ") } +func findMyIP() (string, error) { + ifaces, err := net.Interfaces() + if err != nil { + return "", err + } + + for _, iface := range ifaces { + if iface.Flags&net.FlagUp == 0 { + continue // interface down + } + if iface.Flags&net.FlagLoopback != 0 { + continue // loopback interface + } + + addrs, err := iface.Addrs() + if err != nil { + return "", err + } + + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + if ip == nil || ip.IsLoopback() { + continue + } + ip = ip.To4() + if ip == nil { + continue // not an ipv4 address + } + return ip.String(), nil + } + } + return "", errors.New("not connected to networks") +} + func init() { client = new(http.Client) - - env = os.Getenv("TKPENV") } // CaptureHandler handle panic on http handler. @@ -123,7 +172,7 @@ func Capture(err string, message string) { func publishError(errs error, reqBody []byte, withStackTrace bool) { errorStack := debug.Stack() - t := fmt.Sprintf(`[%s] *%s*`, env, errs.Error()) + t := fmt.Sprintf(`[%s|%s] *%s*`, env, ipAddress, errs.Error()) if len(tagString) > 0 { t = t + " | " + tagString