A
A
Alexey2018-06-16 08:22:08
go
Alexey, 2018-06-16 08:22:08

How to log an error in Go (Panic, etc.) at which the server crashes?

Hello.
If I run a goprogram from the command line - in case of some error - I see a result like

panic: runtime error: invalid memory address or nil pointer

When you run ./main > log.txt - this data instead of the log gets into the console, from where it was launched.
When launched using Supervisor, this data is also not displayed in the log.
How can I then find out why the server crashed, how to log these errors?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2018-06-16
@babderos

You can also run it like this:
then both stderr and stdout will be poured into log.txt
If they are needed separately, then like this:
./main 2>errors.txt >log.txt

A
Alexey, 2018-06-16
@babderos

Found a solution
For unix systems, a function is created

func redirectStderr(f *os.File) {
    err := syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
    if err != nil {
        log.Fatalf("Failed to redirect stderr to file: %v", err)
    }
}

And then in main() I start redirecting error output to a file or Stdout
redirectStderr(os.Stdout)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question