Convert Figma logo to code with AI

maruel logopanicparse

Crash your app in style (Golang)

3,520
99
3,520
3

Top Related Projects

errcheck checks that you checked errors.

It's like curl -v, with colours.

7,344

[mirror] Go Tools

3,974

[mirror] This is a linter for Go source code. (deprecated)

Staticcheck - The advanced Go linter

Quick Overview

panicparse is a Go library that helps analyze and format Go panic stack traces. It can group similar goroutines together, making it easier to understand and debug complex Go applications.

Pros

  • Improved Readability: panicparse formats panic stack traces in a more readable and organized manner, making it easier to identify the root cause of issues.
  • Goroutine Grouping: The library can group similar goroutines together, reducing the amount of information displayed and highlighting the unique parts of each goroutine.
  • Customizable Output: panicparse provides various output options, allowing users to customize the format of the panic stack trace to suit their needs.
  • Supports Multiple Platforms: The library is cross-platform and can be used on Windows, macOS, and Linux.

Cons

  • Limited to Go: panicparse is specifically designed for Go applications and may not be applicable to projects in other programming languages.
  • Dependency on Go Runtime: The library relies on the Go runtime to provide information about the panic stack trace, which means it may not work as expected in certain edge cases or with custom Go runtime configurations.
  • Potential Performance Impact: Depending on the size and complexity of the panic stack trace, the processing performed by panicparse may have a noticeable impact on the overall performance of the application.
  • Lack of Advanced Features: While panicparse provides basic functionality for analyzing and formatting panic stack traces, it may not offer more advanced features or integrations that some users might require.

Code Examples

Here are a few examples of how to use panicparse in your Go code:

  1. Parsing a Panic Stack Trace:
package main

import (
    "fmt"
    "github.com/maruel/panicparse"
)

func main() {
    stack := `goroutine 1 [running]:
main.main()
    /path/to/file.go:10 +0x80
`

    stacks, err := panicparse.Stack([]byte(stack))
    if err != nil {
        fmt.Println("Error parsing stack trace:", err)
        return
    }

    fmt.Println(stacks)
}
  1. Grouping Similar Goroutines:
package main

import (
    "fmt"
    "github.com/maruel/panicparse"
)

func main() {
    stack := `goroutine 1 [running]:
main.main()
    /path/to/file.go:10 +0x80

goroutine 2 [running]:
main.someFunction()
    /path/to/file.go:15 +0x90

goroutine 3 [running]:
main.someFunction()
    /path/to/file.go:15 +0x90
`

    stacks, err := panicparse.Stack([]byte(stack))
    if err != nil {
        fmt.Println("Error parsing stack trace:", err)
        return
    }

    groups := panicparse.Aggregate(stacks)
    fmt.Println(groups)
}
  1. Customizing the Output:
package main

import (
    "fmt"
    "github.com/maruel/panicparse"
)

func main() {
    stack := `goroutine 1 [running]:
main.main()
    /path/to/file.go:10 +0x80

goroutine 2 [running]:
main.someFunction()
    /path/to/file.go:15 +0x90
`

    stacks, err := panicparse.Stack([]byte(stack))
    if err != nil {
        fmt.Println("Error parsing stack trace:", err)
        return
    }

    output := panicparse.Output{
        Stdout: true,
        Stderr: false,
        Color:  true,
    }

    if err := output.Print(stacks); err != nil {
        fmt.Println("Error printing stack trace:", err)
    }
}

Getting Started

To use panicparse in your Go project, follow these steps:

Competitor Comparisons

errcheck checks that you checked errors.

Pros of errcheck

  • Provides a comprehensive check for unchecked errors in Go code, helping to ensure better error handling.
  • Supports a wide range of error-handling patterns, including the use of defer statements.
  • Offers customizable rules and exclusions, allowing developers to tailor the tool to their specific needs.

Cons of errcheck

  • Does not provide the same level of detailed analysis and visualization as panicparse, which can be helpful for understanding complex panic situations.
  • May not be as user-friendly or intuitive as panicparse, especially for developers who are not familiar with the tool.
  • Focuses solely on error checking, while panicparse provides a broader set of features for analyzing and understanding panics in Go applications.

Code Comparison

panicparse

func main() {
    panic("something went wrong")
}

errcheck

func main() {
    _, err := os.Open("file.txt")
    if err != nil {
        fmt.Println(err)
    }
}

It's like curl -v, with colours.

Pros of httpstat

  • Provides a simple and intuitive way to display HTTP response statistics
  • Supports a wide range of HTTP status codes and response information
  • Offers a clean and easy-to-read output format

Cons of httpstat

  • Limited functionality compared to panicparse, which is a more comprehensive tool
  • Doesn't provide the same level of detailed analysis and debugging capabilities as panicparse

Code Comparison

panicparse:

func parseStack(stack []byte) ([]Frame, error) {
    var frames []Frame
    var currentFrame *Frame
    for _, line := range bytes.Split(stack, []byte{'\n'}) {
        if len(line) == 0 {
            continue
        }
        if bytes.HasPrefix(line, []byte("goroutine ")) {
            if currentFrame != nil {
                frames = append(frames, *currentFrame)
            }
            currentFrame = &Frame{
                ID: parseGoroutineID(line),
            }
        } else {
            if currentFrame == nil {
                return nil, fmt.Errorf("unexpected line: %s", line)
            }
            currentFrame.Calls = append(currentFrame.Calls, parseLine(line))
        }
    }
    if currentFrame != nil {
        frames = append(frames, *currentFrame)
    }
    return frames, nil
}

httpstat:

func main() {
    url := os.Args[1]
    resp, err := http.Get(url)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s\n", err)
        os.Exit(1)
    }
    defer resp.Body.Close()

    fmt.Printf("URL: %s\n", url)
    fmt.Printf("Status: %s\n", resp.Status)
    fmt.Printf("Protocol: %s\n", resp.Proto)
    fmt.Printf("Time: %s\n", time.Since(start))
    fmt.Printf("DNS+dialup: %s\n", resp.Header.Get("X-Httpstat-Resolve"))
    fmt.Printf("TCP: %s\n", resp.Header.Get("X-Httpstat-Connect"))
    fmt.Printf("TLS: %s\n", resp.Header.Get("X-Httpstat-Tls"))
    fmt.Printf("Server processing: %s\n", resp.Header.Get("X-Httpstat-Process"))
    fmt.Printf("Content transfer: %s\n", resp.Header.Get("X-Httpstat-Transfer"))
}
7,344

[mirror] Go Tools

Pros of golang/tools

  • Comprehensive set of tools for Go development, including a wide range of utilities for linting, formatting, and analyzing Go code.
  • Actively maintained and updated by the Go team, ensuring compatibility with the latest Go versions.
  • Provides a centralized location for Go-related tools, making it easier for developers to discover and use them.

Cons of golang/tools

  • The repository can be overwhelming for new Go developers, as it contains a large number of tools and utilities.
  • Some tools within the repository may have overlapping functionality, which can make it difficult to choose the right tool for a specific task.

Code Comparison

Here's a brief code comparison between a function from panicparse and a function from golang/tools:

// From panicparse
func parseStack(stack []byte) ([]Frame, error) {
    var frames []Frame
    for _, line := range bytes.Split(stack, []byte{'\n'}) {
        if len(line) == 0 {
            continue
        }
        frame, err := parseFrame(line)
        if err != nil {
            return nil, err
        }
        frames = append(frames, frame)
    }
    return frames, nil
}
// From golang/tools
func (c *Config) Lint(fset *token.FileSet, files []*ast.File) []Diagnostic {
    var diagnostics []Diagnostic
    for _, f := range files {
        for _, d := range c.lintFile(fset, f) {
            diagnostics = append(diagnostics, d)
        }
    }
    return diagnostics
}

Both functions are responsible for parsing and processing data, but they serve different purposes within their respective projects.

3,974

[mirror] This is a linter for Go source code. (deprecated)

Pros of golang/lint

  • golang/lint is an official Go project, maintained by the Go team, ensuring high-quality and up-to-date linting for Go code.
  • The project has a large user base and is widely adopted in the Go community, making it a reliable and well-supported tool.
  • golang/lint provides a comprehensive set of linting rules and checks, covering a wide range of code quality and style aspects.

Cons of golang/lint

  • maruel/panicparse may offer more advanced features and customization options compared to the more basic linting provided by golang/lint.
  • The integration and configuration of golang/lint may be more complex, especially for projects with specific linting requirements.

Code Comparison

// golang/lint
func (f *File) Lint(fset *token.FileSet) []Failure {
    var failures []Failure
    for _, decl := range f.Decls {
        switch d := decl.(type) {
        case *ast.FuncDecl:
            failures = append(failures, f.lintFuncDecl(fset, d)...)
        case *ast.GenDecl:
            failures = append(failures, f.lintGenDecl(fset, d)...)
        }
    }
    return failures
}
// maruel/panicparse
func (s *Stack) Normalize() {
    for i := range s.Frames {
        s.Frames[i].Normalize()
    }
    s.Normalize2()
}

func (f *Frame) Normalize() {
    f.Function = strings.TrimPrefix(f.Function, "github.com/")
    f.Function = strings.TrimPrefix(f.Function, "golang.org/")
}

Staticcheck - The advanced Go linter

Pros of go-tools

  • go-tools provides a wide range of tools for Go development, including linters, code formatters, and static analysis tools.
  • The project is actively maintained and has a large community of contributors.
  • go-tools integrates well with popular IDEs and text editors, making it easy to use in a development workflow.

Cons of go-tools

  • The project can be overwhelming for beginners, as it includes a large number of tools and features.
  • Some of the tools in go-tools may overlap with functionality provided by other Go tools, which can be confusing for users.

Code Comparison

Here's a brief comparison of the code for the panicparse package in maruel/panicparse and the staticcheck package in dominikh/go-tools:

// maruel/panicparse
func parseStack(stack []byte) ([]Frame, error) {
    var frames []Frame
    var frame Frame
    var inFrame bool
    for _, line := range bytes.Split(stack, []byte{'\n'}) {
        if len(line) == 0 {
            continue
        }
        if bytes.HasPrefix(line, []byte{' ', '\t'}) {
            if !inFrame {
                return nil, fmt.Errorf("unexpected line: %s", line)
            }
            frame.Lines = append(frame.Lines, string(line))
        } else {
            if inFrame {
                frames = append(frames, frame)
            }
            frame = Frame{
                Func: string(bytes.TrimSpace(line)),
            }
            inFrame = true
        }
    }
    if inFrame {
        frames = append(frames, frame)
    }
    return frames, nil
}
// dominikh/go-tools/staticcheck
func (c *Checker) checkAssignmentToNil(f *token.File, stmt *ast.AssignStmt) {
    if len(stmt.Lhs) != 1 || len(stmt.Rhs) != 1 {
        return
    }
    lhs, ok := stmt.Lhs[0].(*ast.Ident)
    if !ok {
        return
    }
    rhs, ok := stmt.Rhs[0].(*ast.Ident)
    if !ok {
        return
    }
    if rhs.Name == "nil" && c.isNil(lhs) {
        c.report(f, stmt.Pos(), "assignment to nil")
    }
}

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

panicparse

Parses panic stack traces, densifies and deduplicates goroutines with similar stack traces. Helps debugging crashes and deadlocks in heavily parallelized process.

PkgGoDev codecov go-recipes

panicparse helps make sense of Go crash dumps:

Screencast

Features

  • Race detector support, e.g. it can parse output produced by go test -race
  • HTML export.
  • Easy to use as an HTTP Handler middleware.
  • High performance parsing.
  • HTTP web server that serves a very tight and swell snapshot of your goroutines, much more readable than net/http/pprof.
  • >50% more compact output than original stack dump yet more readable.
  • Deduplicates redundant goroutine stacks. Useful for large server crashes.
  • Arguments as pointer IDs instead of raw pointer values.
  • Pushes stdlib-only stacks at the bottom to help focus on important code.
  • Parses the source files if available to augment the output.
  • Works on any platform supported by Go, including Windows, macOS, linux.
  • Full go module support.
  • Requires >=go1.17. Use v2.3.1 for older Go versions.

Installation

go install github.com/maruel/panicparse/v2/cmd/pp@latest

Usage

Piping a stack trace from another process

TL;DR

  • Ubuntu (bash v4 or zsh): |&
  • macOS, install bash 4+, then: |&
  • Windows or macOS with stock bash v3: 2>&1 |
  • Fish shell: &|

Longer version

pp streams its stdin to stdout as long as it doesn't detect any panic. panic() and Go's native deadlock detector print to stderr via the native print() function.

Bash v4 or zsh: |& tells the shell to redirect stderr to stdout, it's an alias for 2>&1 | (bash v4, zsh):

go test -v |&pp

Windows or macOS native bash (which is 3.2.57): They don't have this shortcut, so use the long form:

go test -v 2>&1 | pp

Fish: &| redirects stderr and stdout. It's an alias for 2>&1 | (fish piping):

go test -v &| pp

PowerShell: It has broken 2>&1 redirection. The workaround is to shell out to cmd.exe. :(

Investigate deadlock

On POSIX, use Ctrl-\ to send SIGQUIT to your process, pp will ignore the signal and will parse the stack trace.

Parsing from a file

To dump to a file then parse, pass the file path of a stack trace

go test 2> stack.txt
pp stack.txt

Tips

Disable inlining

The Go toolchain inlines functions when it can. This causes traces to be less informative. Optimization also interfere with traces. You can use the following to help diagnosing issues:

go install -gcflags '-N -l' path/to/foo
foo |& pp

or

go test -gcflags '-N -l' ./... |& pp

Run go tool compile -help to get the full list of valid values for -gcflags.

GOTRACEBACK

By default, GOTRACEBACK defaults to single, which means that a panic will only return the current goroutine trace alone. To get all goroutines trace and not just the crashing one, set the environment variable:

export GOTRACEBACK=all

or set GOTRACEBACK=all on Windows. Probably worth to put it in your .bashrc.

Updating bash on macOS

Install bash v4+ on macOS via homebrew or macports. Your future self will appreciate having done that.

If you have /usr/bin/pp installed

If you try pp for the first time and you get:

Creating tables and indexes...
Done.

and/or

/usr/bin/pp5.18: No input files specified

you may be running the Perl PAR Packager instead of panicparse.

You have two choices, either you put $GOPATH/bin at the beginning of $PATH or use long name panicparse with:

go install github.com/maruel/panicparse/v2@latest

then using panicparse instead of pp:

go test 2> panicparse

Hint: You may also use shell aliases

alias gp=panicparse
go test 2> gp

alias p=panicparse
go test 2> p

webstack in action

The webstack.SnapshotHandler http.Handler enables glancing at at a snapshot of your process trivially:

Screencast

Authors

panicparse was created with ❤️️ and passion by Marc-Antoine Ruel and friends.