├── example └── test.go ├── dump_stack.go └── README.md /example/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/rfyiamcool/dump_stack" 7 | ) 8 | 9 | func main() { 10 | dumpStack.SetupStackTrap() 11 | time.Sleep(100 * time.Second) 12 | } 13 | -------------------------------------------------------------------------------- /dump_stack.go: -------------------------------------------------------------------------------- 1 | package dumpStack 2 | 3 | import ( 4 | "os" 5 | "os/signal" 6 | "runtime" 7 | "syscall" 8 | "time" 9 | ) 10 | 11 | // how to use? 12 | // kill -USR1 pid 13 | // tail stack.log 14 | 15 | const ( 16 | timeFormat = "2006-01-02 15:04:05" 17 | ) 18 | 19 | var ( 20 | stdFile = "./stack.log" 21 | ) 22 | 23 | func SetupStackTrap(args ...string) { 24 | if len(args) > 0 { 25 | stdFile = args[0] 26 | } 27 | 28 | c := make(chan os.Signal, 1) 29 | signal.Notify(c, syscall.SIGUSR1) 30 | go func() { 31 | for range c { 32 | dumpStacks() 33 | } 34 | }() 35 | } 36 | 37 | func dumpStacks() { 38 | buf := make([]byte, 1638400) 39 | buf = buf[:runtime.Stack(buf, true)] 40 | writeStack(buf) 41 | } 42 | 43 | func writeStack(buf []byte) { 44 | fd, _ := os.OpenFile(stdFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) 45 | 46 | now := time.Now().Format(timeFormat) 47 | fd.WriteString("\n\n\n\n\n") 48 | fd.WriteString(now + " stdout:" + "\n\n") 49 | fd.Write(buf) 50 | fd.Close() 51 | } 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # stack_dump 2 | 3 | import stack_dump module, receive signal `USR1`, dump golang all goroutine stack content to file. 4 | 5 | ### how to use? 6 | 7 | *use stack_dump module* 8 | 9 | ``` 10 | package main 11 | 12 | import ( 13 | "time" 14 | 15 | "github.com/rfyiamcool/dump_stack" 16 | ) 17 | 18 | func main() { 19 | dumpStack.SetupStackTrap() 20 | // dumpStack.SetupStackTrap("stack.log") 21 | time.Sleep(100 * time.Second) 22 | } 23 | ``` 24 | 25 | *dump golang goroutine stack* 26 | 27 | ``` 28 | kill -USR1 pid 29 | tail stack.log 30 | ``` 31 | 32 | *analyse top func* 33 | 34 | ``` 35 | awk -F '[' '/goroutine \d*/{print "[" $2}' stack.log | sort | uniq -c | sort -k1nr | head -20 36 | 37 | 5030 [select]: 38 | 1910 [semacquire]: 39 | 952 [IO wait]: 40 | 198 [chan send]: 41 | 11 [sleep]: 42 | 3 [runnable]: 43 | 2 [chan receive, 6 minutes]: 44 | 2 [select, 6 minutes]: 45 | 1 [chan receive]: 46 | 1 [IO wait, 1 minutes]: 47 | 1 [running]: 48 | 1 [select, 6 minutes, locked to thread]: 49 | 1 [syscall]: 50 | ``` 51 | --------------------------------------------------------------------------------