go工具pprof使用应用程序PID而不是http端点



现在,我使用Go工具pprof来配置Go应用程序,如下所示:

go tool pprof http://localhost:8080/debug/pprof/profile

我想在一个未知端口上运行http服务器的任意Go进程上使用pprof工具。我所知道的关于这个进程的唯一信息是它的PID。我需要做两件事中的一件:

  • 从Go进程的PID中获取端口号
  • 直接配置正在运行的进程。例如,go tool pprof 10303的PID是10303。

这两种方法都可以吗?

Service Discovery就是为解决这类问题而设计的。一个简单的解决方案是为每个PID创建一个tmp文件,将每个端口写入相应的文件。当需要go tool pprof时读取端口

http.ListenAndServe("localhost:" + PORT, nil)
tmpFilePath := filePath.Join(os.TempDir(), "myport_" + strconv.FormatInt(os.Getpid(), 10))
f, _ := os.OpenFile(tmpFilePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
f.Write(byte[](strconv.FormatInt(PORT, 10)))
f.Close()

在go tool prof bash: go tool http://localhost: ' cat/tmp/myport_10303 '/debug/pprof/profile

没有实际测试,可能是语法错误

更新:

另一种不改变go源的方法是,使用bash命令如netstat/lsof来查找go进程的侦听端口。如:

netstat -antp | grep 10303| grep LISTEN | awk '{ print $4 }' | awk -F: '{print $2}'

不是最好的bash脚本,仅供参考。

最新更新