哪里写恐慌日志?

时间:2014-06-09 04:06:09

标签: logging go

我通过epel在redhat服务器上安装了golang。我正在尝试分析恐慌日志,但我找不到日志的存储位置。任何提示? / var / log

中没有跟踪
      func main() {

            http.HandleFunc("/", panicRecover(test))
            log.Fatal(http.ListenAndServe(":80", nil))
        }



    func test(){
        out, err := exec.Command("echo ", "something").Output()
            if err != nil {
                log.Panic(err)

            }
    }


func panicRecover(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if r := recover(); r != nil {
                log.Printf("PANIC RECOVERED:%s\n", r)
            }
        }()
        f(w, r)
    }

2 个答案:

答案 0 :(得分:7)

stderr

例如,

package main

import "log"

func main() {
    log.Panic("log.Panic to stderr")
}


$ go run panic.go 2>stderr.txt

stderr.txt文件:

2014/06/09 00:30:54 log.Panic to stderr
panic: log.Panic to stderr

goroutine 16 [running]:
runtime.panic(0x497180, 0xc2080001a0)
    /home/peter/go/src/pkg/runtime/panic.c:279 +0xf5
log.Panic(0x7f88770fff20, 0x1, 0x1)
    /home/peter/go/src/pkg/log/log.go:307 +0xb6
main.main()
    /home/peter/gopath/src/so/panic.go:6 +0xa7

goroutine 17 [runnable]:
runtime.MHeap_Scavenger()
    /home/peter/go/src/pkg/runtime/mheap.c:507
runtime.goexit()
    /home/peter/go/src/pkg/runtime/proc.c:1445

goroutine 18 [runnable]:
bgsweep()
    /home/peter/go/src/pkg/runtime/mgc0.c:1976
runtime.goexit()
    /home/peter/go/src/pkg/runtime/proc.c:1445

goroutine 19 [runnable]:
runfinq()
    /home/peter/go/src/pkg/runtime/mgc0.c:2606
runtime.goexit()
    /home/peter/go/src/pkg/runtime/proc.c:1445
exit status 2

答案 1 :(得分:3)

默认情况下,它将它们写入stderr。您可以使用log.SetOutput(os.Writer)更改此设置。如果您不想在命令行上使用2>(比如它是您计划从GUI文件系统而不是终端运行的用户的应用程序),那么登录文件的好方法涉及使用init在主程序开始之前运行的事实。

例如,您可以

package main

import (
    "log"
    "os"
)

var logFile os.File

func init() {
    var err error
    // Of course, this name isn't unique,
    // I usually use time.Now().Unix() or something
    // to get unique log names.
    logFile,err = os.Create("logfile.txt")
    if err != nil {
        // Open a different logfile or something
    }
    log.SetOutput(logFile)
}

困难在于,如果你发生恐慌,你应该总是恢复,以确保你Close该文件。如果您使用bufio进行缓冲日志记录,尤其如此,如果程序发生混乱,您可能无法在未明确刷新缓冲区的情况下看到最新数据。