stackparse

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2024 License: MIT Imports: 8 Imported by: 0

README

stackparse

Codacy Badge

A Go library for parsing and formatting stack traces with powerful customization options. This library makes debugging crashes and deliberate stack dumps more manageable by providing beautifully formatted stack traces with customizable styling.

Installation

go get github.com/kociumba/stackparse

Basic Usage

The simplest way to use stackparse is to capture and parse a stack trace:

package main

import (
    "os"
    "runtime"
    "github.com/kociumba/stackparse"
)

func main() {
    // Create a buffer for the stack trace
    buf := make([]byte, 1<<16)
    
    // Capture the stack trace
    runtime.Stack(buf, true)
    
    // Parse and format the stack trace
    parsed := stackparse.Parse(buf)
    // modify the buffer in place with:
    stackparse.ParseStatic(&buf)
    
    // Write to stderr (or any other output)
    os.Stderr.Write(parsed)
    // if using stackparse.ParseStatic(), simply write from the buffer
    os.Stderr.Write(buf)
}

[!IMPORTANT] Right now stackparse does not parse the reason given when when calling panic(), but this is planned for the next release.

Configuration Options

stackparse provides several configuration options to customize the output:

[!NOTE] Default settings are: Colorize: true, Simple: true, Theme: stackparse.DefaultTheme()

Colorization

Control whether the output includes ANSI color codes:

// Disable coloring the output
parsed := stackparse.Parse(buf, stackparse.WithColor(false))
Simple Mode

Toggle between simple and detailed output formats (shortens both the function names and file paths):

// Disable simple mode for more detailed output, does not guarantee that the formatting will be correct in all cases
parsed := stackparse.Parse(buf, stackparse.WithSimple(false))

Theming

stackparse uses lipgloss for styling and provides powerful theming capabilities.

Using the Default Theme

The default theme provides a color scheme based on the catppuccin theme.

// Stackparse uses the default theme without having to pass it in
parsed := stackparse.Parse(buf)

// You can get the default theme like this
defaultTheme := stackparse.DefaultTheme()
Custom Themes

You can create custom themes by modifying the default theme or creating a new one from scratch:

// Create a custom theme based on the default
myTheme := stackparse.DefaultTheme()

// overwrite the default styles compleatly
myTheme.Goroutine = lipgloss.NewStyle().
    Bold(true).
    Foreground(lipgloss.Color("#ff0000")) // Red goroutine labels

myTheme.Function = lipgloss.NewStyle().
    Foreground(lipgloss.Color("#00ff00")). // Green function names
    Italic(true)

// or build on top of the default theme
myTheme.Repeat = myTheme.Repeat.Faint(true).Blink(true) 

// Apply the custom theme
parsed := stackparse.Parse(buf, stackparse.WithTheme(myTheme))
Theme Components

The Theme struct provides the following customizable components:

  • Goroutine: Styling for goroutine headers
  • Function: Styling for function names
  • Args: Styling for function arguments
  • File: Styling for file paths
  • Line: Styling for line numbers
  • CreatedBy: Styling for "created by" sections
  • Repeat: Styling for repeated stack frames
Custom Style Disabling

You can control how styles are disabled when colors are turned off with:

myTheme := stackparse.DefaultTheme()

// Custom disable function
myTheme.SetDisableStylesFunc(func(t *stackparse.Theme) {
    // Keep bold formatting but remove colors
    t.Goroutine = t.Goroutine.UnsetForeground()
    t.Function = t.Function.UnsetForeground()
    t.Repeat = t.Repeat.UnsetBlink().UnsetFeint()
    
    // Keep some styling intact
    // everything else remains unchanged
})

parsed := stackparse.Parse(buf, 
    stackparse.WithTheme(myTheme),
    stackparse.WithColor(false), // This will trigger the custom disable function
)

Output Example

When using the default theme, your stack trace will be formatted like this:

default styling

Contributing

Contributions are welcome! Please feel free to submit a Pull Request with anything: fixes, demos, improvements, etc.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(stack []byte, options ...Option) []byte

Parse is the main entry point for parsing stack traces

You can use this to parse stack traces from your code like this:

buf := make([]byte, 1<<16)
runtime.Stack(buf, true)
parsed := stackparse.Parse(buf)
// use the parsed stack however you want
// the return is also []byte, so you can do things like:
os.Stderr.Write(parsed)

func ParseStatic added in v0.0.3

func ParseStatic(stack *[]byte, options ...Option)

Use this to parse the stack trace in place overwriting the original buffer

buf := make([]byte, 1<<16)
runtime.Stack(buf, true)
stackparse.Parse(&buf)
os.Stderr.Write(buf)

Types

type Config added in v0.0.2

type Config struct {
	Colorize bool
	Simple   bool
	Theme    *Theme
}

Config holds all configuration options for the parser

func NewConfig added in v0.0.2

func NewConfig() *Config

NewConfig creates a new configuration with default values

Mostly used internally but exposed for some edge cases

type Formatter added in v0.0.2

type Formatter struct {
	// contains filtered or unexported fields
}

Formatter handles the formatting of parsed stack traces

func NewFormatter added in v0.0.2

func NewFormatter(config *Config) *Formatter

NewFormatter creates a new Formatter instance

Mostly used internally, but exposed for some edge cases

func (*Formatter) Format added in v0.0.2

func (f *Formatter) Format(traces []*StackTrace) string

Format converts a StackTrace into a formatted string

If you are using this by itself without calling stackparse.Parse(), you should call this after the parser.

type Option

type Option func(*Config)

Option is a function type for setting configuration options

func WithColor added in v0.0.2

func WithColor(enabled bool) Option

WithColor enables or disables colorized output

func WithSimple added in v0.0.2

func WithSimple(enabled bool) Option

WithSimple enables or disables simplified output

func WithTheme added in v0.0.2

func WithTheme(theme *Theme) Option

WithTheme sets a custom theme

type Parser added in v0.0.2

type Parser struct {
	// contains filtered or unexported fields
}

Parser handles the parsing of stack traces

func NewParser added in v0.0.2

func NewParser(options ...Option) *Parser

NewParser creates a new Parser instance with the given options

Mostly used internally but exposed for some edge cases

func (*Parser) Parse added in v0.0.2

func (p *Parser) Parse(stack []byte) []*StackTrace

Parse converts a byte slice containing a stack trace into a StackTrace

I you are usting this by itself and not by simply calling stackparse.Parse(), always call this before the formatter.

type Patterns added in v0.0.2

type Patterns struct {
	Goroutine *regexp.Regexp
	Function  *regexp.Regexp
	Location  *regexp.Regexp
	CreatedBy *regexp.Regexp
	LongFunc  *regexp.Regexp
}

Patterns holds all regex patterns used for parsing

type StackEntry added in v0.0.2

type StackEntry struct {
	FunctionName       string
	FullName           string
	Args               string
	File               string
	Line               string
	Offset             string
	IsCreatedBy        bool
	CreatedByGoroutine string
}

StackEntry represents a single entry in the stack trace

type StackTrace added in v0.0.2

type StackTrace struct {
	Entries        []StackEntry
	GoroutineID    string
	GoroutineState string
}

StackTrace represents a complete stack trace

type StyleDisabler added in v0.0.3

type StyleDisabler interface {
	DisableStyles()
}

StyleDisabler represents types that can disable their styles

type Theme added in v0.0.2

type Theme struct {
	Base      lipgloss.Style
	Goroutine lipgloss.Style
	Function  lipgloss.Style
	Args      lipgloss.Style
	File      lipgloss.Style
	Line      lipgloss.Style
	CreatedBy lipgloss.Style
	Repeat    lipgloss.Style
	// contains filtered or unexported fields
}

Theme defines the styling for different components

You can provide you own theme to stackparse, and all of the output will be styled accordingly Setting a custom DisableStylesFunc is not required but if you want to preserve specific styling, you can do so. Usage would look something like this.

Method 1: Using SetDisableStylesFunc:

	theme := stackparse.DefaultTheme()
	theme.SetDisableStylesFunc(func(t *stackparse.Theme) {
 	// Custom implementation
 	t.Base = t.Base.UnsetForeground()
 	t.Function = t.Function.UnsetBold()
 	// ... other custom unset operations
	})

Method 2: Creating a custom theme with custom disable function:

	customTheme := &stackparse.Theme{
 	// ... theme settings ...
	}
	customTheme.SetDisableStylesFunc(func(t *stackparse.Theme) {
 	// Custom implementation
	})

func DefaultTheme added in v0.0.2

func DefaultTheme() *Theme

DefaultTheme returns the default styling theme

func (*Theme) DisableStyles added in v0.0.3

func (t *Theme) DisableStyles()

DisableStyles disables all color and text styles (e.g. bold, underline, etc.) of a theme

When providing your own theme, you can use this default or create your own DisableStyles to unset only specific styling.

Keep in mind you need to reassign the styles after unsetting parts of them, for example:

func (t *Theme) DisableStyles() {
	t.Base = t.Base.UnsetForeground()
}

func (*Theme) SetDisableStylesFunc added in v0.0.3

func (t *Theme) SetDisableStylesFunc(f func(*Theme))

SetDisableStylesFunc allows setting a custom DisableStyles implementation

For more info read the documentation of

Theme{}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL