0

I use logger in my program defined from pattern as below

var (
    logFile *os.File
    Info    *log.Logger
)

func init() {
    var err error
    logFile, err = os.OpenFile("/my/file/with.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
    if err != nil {
        fmt.Printf("Cannot open log file error:%s. Program was terminated.", err)
        os.Exit(1)
    }
    Info = log.New(logFile,
        "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
 }

Now I would like write all information from stackTrace if these occured for example from panic() to my log file. Now if some gone was wrong all this information are print to console in my IDE, but if porgram works on server, I lose information if occured some null pointer, wrong pass argument to function, that's why I want write this information to log file. It is possible ?

Mbded
  • 1,754
  • 4
  • 23
  • 43
  • 1
    You should be redirecting stderr and stdout to a file on the server (or into some other logging mechanism). You set `os.Stderr` to another file in your app, but it's going to be more reliable to have that managed externally. – JimB Oct 19 '16 at 15:19
  • This is a key. A tried find some function to this in golang doc, but for now nothing. A tried for eg `os.Stderr = os.NewFile(uintptr(syscall.Stderr), "/my/log/file.log")` but dosen't works. I will be trying still something other... unles someone will be faster, and find solution before me – Mbded Oct 19 '16 at 19:51
  • `os.NewFile` just returns a new `*os.File` with that file descriptor, so it did nothing except change string returned by `os.Stderr.Name()` – JimB Oct 19 '16 at 20:09
  • I found solution http://stackoverflow.com/questions/34772012/capturing-panic-in-golang this I looking for. – Mbded Oct 21 '16 at 20:47

1 Answers1

0

Use syscall.Dup2 to link the opened file to the standard stream

func main() {
   syscall.Dup2(int(logFile.Fd()), 2)
}

or create panic handler

defer func() {
        err := recover()
        if err != nil {
            //...
        }
    }()
Marsel Novy
  • 1,777
  • 16
  • 23
  • You can't create a "global panic handler", because you can only recover within the panicking goroutine. – JimB Oct 19 '16 at 15:41