Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重定向运行时panic到文件 #19

Open
kevinyan815 opened this issue Sep 13, 2020 · 1 comment
Open

重定向运行时panic到文件 #19

kevinyan815 opened this issue Sep 13, 2020 · 1 comment

Comments

@kevinyan815
Copy link
Owner

package main

import (
	"fmt"
	"os"
	"runtime"
	"syscall"
)

const stdErrFile = "/tmp/go-app1-stderr.log"

var stdErrFileHandler *os.File

func RewriteStderrFile() error {
	if runtime.GOOS == "windows" {
		return nil
	}

	file, err := os.OpenFile(stdErrFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println(err)
		return err
	}
	stdErrFileHandler = file //把文件句柄保存到全局变量,避免被GC回收

	if err = syscall.Dup2(int(file.Fd()), int(os.Stderr.Fd())); err != nil {
		fmt.Println(err)
		return err
	}
	// 内存回收前关闭文件描述符
	runtime.SetFinalizer(stdErrFileHandler, func(fd *os.File) {
		fd.Close()
	})

	return nil
}

func testPanic() {
	panic("test panic")
}

func main() {
	RewriteStderrFile()
	testPanic()
}
@kevinyan815 kevinyan815 changed the title 重定向panic到文件 重定向运行时panic到文件 Sep 13, 2020
@Browinee
Copy link

感謝分享,很少看到系統層面的應用!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants