gops 工具使用方法
gops 是 Go 官方提供的一个用于诊断和分析运行中 Go 程序的工具集,由 Go 核心团队开发。以下是 gops 的主要功能和使用方法:
安装
go install github.com/google/gops@latest
基本使用
1. 监控本地运行的 Go 进程
gops
这会列出所有正在运行的 Go 进程,显示它们的 PID、构建版本和程序路径。
2. 附加到特定进程
gops <pid>
这会显示指定进程的详细信息,包括:
- Go 版本
 - Goroutine 数量
 - 线程数量
 - GC 统计信息
 - 内存使用情况
 
3. 堆栈跟踪
获取进程的堆栈跟踪:
gops stack <pid>
或者输出到文件:
gops stack <pid> > stack.txt
4. 内存统计
获取内存统计信息:
gops memstats <pid>
5. 性能分析
启动 CPU 分析(默认 30 秒):
gops pprof-cpu <pid>
启动堆内存分析:
gops pprof-heap <pid>
6. 程序内集成
要在你的程序中启用 gops 代理(允许远程诊断):
import "github.com/google/gops/agent"
func main() {
    if err := agent.Listen(agent.Options{}); err != nil {
        log.Fatal(err)
    }
    // 你的程序逻辑...
}
这样你的程序会监听一个本地端口,gops 工具可以自动发现并连接。
高级功能
远程诊断
如果程序集成了 gops agent 并配置了可远程访问:
gops -remote=1.2.3.4:1234 <command> <pid>
火焰图生成
结合 pprof 生成火焰图:
gops pprof-cpu <pid> > cpu.pprof
go tool pprof -http=:8080 cpu.pprof
常用命令总结
| 命令 | 描述 | 
|---|---|
gops | 
列出所有 Go 进程 | 
gops <pid> | 
显示进程详情 | 
gops stack <pid> | 
获取堆栈跟踪 | 
gops memstats <pid> | 
查看内存统计 | 
gops gc <pid> | 
强制 GC | 
gops version <pid> | 
查看 Go 版本 | 
gops stats <pid> | 
查看运行时统计 | 
gops trace <pid> | 
开始执行跟踪 | 
gops 是一个强大的工具,特别适合在生产环境中诊断 Go 应用程序问题,而无需停止或重启服务。
    Do not communicate by sharing memory; instead, share memory by communicating.

                
            
        
浙公网安备 33010602011771号