Skip to content

Commit

Permalink
refactoring, comments, and documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
snwfdhmp committed Feb 20, 2019
1 parent 0d1e70a commit 5d8938d
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 71 deletions.
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# A simple package to enhance Go source code debugging

![Example](https://i.imgur.com/wPBrYqs.png)
![Example](https://i.imgur.com/Ulf1RGw.png)

## Introduction

Expand All @@ -10,8 +10,6 @@ Use errlog to enhance your error logging with :
- Failing func recognition
- Readable stack trace



## Get started

### Install
Expand Down Expand Up @@ -133,11 +131,15 @@ Errlog finds the exact line where the error is defined.

![Source Example: error earlier in the code](https://i.imgur.com/wPBrYqs.png)

## Documentation

Documentation can be found [here on godoc.org](https://github.com/snwfdhmp/errlog).

## Feedback

Feel free to open an issue for any feedback or suggestion.

I fix bugs quickly.
I fix process issues quickly.

## Contributions

Expand Down
43 changes: 1 addition & 42 deletions errlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,13 @@
package errlog

import (
"fmt"
"strconv"
"strings"

"github.com/sirupsen/logrus"
"github.com/spf13/afero"
)

var (
debugMode = false
fs = afero.NewOsFs() //fs is at package level because I think it needn't be scoped to loggers
)

//SetDebugMode sets debug mode to On if toggle==true or Off if toggle==false. It changes log level an so displays more logs about whats happening. Useful for debugging.
Expand All @@ -86,44 +83,6 @@ func SetDebugMode(toggle bool) {
debugMode = toggle
}

var (
fs = afero.NewOsFs() //fs is at package level because I think it needn't be scoped to loggers
)

func parseRef(refLine string) (string, int) {
ref := strings.Split(regexpCodeReference.FindString(refLine), ":")
if len(ref) != 2 {
panic(fmt.Sprintf("len(ref) > 2;ref='%s';", ref))
}

lineNumber, err := strconv.Atoi(ref[1])
if err != nil {
panic(fmt.Sprintf("cannot parse line number '%s': %s", ref[1], err))
}

return ref[0], lineNumber
}

// PrintSourceOptions represents config for (*logger).PrintSource func
type PrintSourceOptions struct {
FuncLine int
StartLine int
EndLine int
Highlighted map[int][]int //map[lineIndex][columnstart, columnEnd] of chars to highlight
}

func (l *logger) printStack(stages []string) {
for i := len(stages) - 1; i >= 0; i-- {
padding := ""
if !l.config.DisableStackIndentation {
for j := 0; j < len(stages)-1-i; j++ {
padding += " "
}
}
l.Printf(" %s%s:%s", padding, regexpCallArgs.FindString(stages[i]), strings.Split(regexpCodeReference.FindString(stages[i]), ":")[1])
}
}

//Debug is a shortcut for DefaultLogger.Debug.
func Debug(uErr error) bool {
DefaultLogger.Overload(1) // Prevents from adding this func to the stack trace
Expand Down
58 changes: 34 additions & 24 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,18 @@ type Config struct {
DisableStackIndentation bool //Shall we print stack vertically instead of indented
}

// PrintSourceOptions represents config for (*logger).PrintSource func
type PrintSourceOptions struct {
FuncLine int
StartLine int
EndLine int
Highlighted map[int][]int //map[lineIndex][columnstart, columnEnd] of chars to highlight
}

//logger holds logger object, implementing Logger interface
type logger struct {
config *Config
stackDepthOverload int
config *Config //config for the logger
stackDepthOverload int //stack depth to ignore when reading stack
}

//NewLogger creates a new logger struct with given config
Expand Down Expand Up @@ -112,11 +121,11 @@ func (l *logger) DebugSource(filepath string, debugLineNumber int) {
lines := strings.Split(string(b), "\n")

// set line range to print based on config values and debugLineNumber
// and correct ouf of range values
minLine := max(debugLineNumber-l.config.LinesBefore, 0)
maxLine := min(debugLineNumber+l.config.LinesAfter, len(lines)-1)
minLine := debugLineNumber - l.config.LinesBefore
maxLine := debugLineNumber + l.config.LinesAfter

deleteBankLinesFromRange(lines, &minLine, &maxLine)
//delete blank lines from range and clean range if out of lines range
deleteBlankLinesFromRange(lines, &minLine, &maxLine)

//free some memory from unused values
lines = lines[:maxLine+1]
Expand Down Expand Up @@ -157,31 +166,20 @@ func (l *logger) PrintSource(lines []string, opts PrintSourceOptions) {
}

for i := opts.StartLine; i < opts.EndLine; i++ {
highlightStart := -1
highlightEnd := -1
if _, ok := opts.Highlighted[i]; ok {
if len(opts.Highlighted[i]) == 2 { //if hightlight slice is in the right format
highlightStart = opts.Highlighted[i][0]
highlightEnd = opts.Highlighted[i][1]
if highlightEnd > len(lines[i])-1 {
highlightEnd = len(lines[i]) - 1
}
} else {
logrus.Debug("len(opts.Highlighted[i]) != 2; skipping highlight")
}
}

if highlightStart == -1 { //simple line
if _, ok := opts.Highlighted[i]; !ok || len(opts.Highlighted[i]) != 2 {
l.Printf("%d: %s", i+1, color.YellowString(lines[i]))
} else { // line with highlightings
logrus.Debugf("Next line should be highlighted from column %d to %d.", highlightStart, highlightEnd)
l.Printf("%d: %s%s%s", i+1, color.YellowString(lines[i][:highlightStart]), color.RedString(lines[i][highlightStart:highlightEnd+1]), color.YellowString(lines[i][highlightEnd+1:]))
continue
}

hlStart := max(opts.Highlighted[i][0], 0) //highlight column start
hlEnd := min(opts.Highlighted[i][1], len(lines)-1) //highlight column end
l.Printf("%d: %s%s%s", i+1, color.YellowString(lines[i][:hlStart]), color.RedString(lines[i][hlStart:hlEnd+1]), color.YellowString(lines[i][hlEnd+1:]))
}
}

func (l *logger) Doctor() (neededDoctor bool) {
neededDoctor = false

if l.config.PrintFunc == nil {
neededDoctor = true
logrus.Debug("PrintFunc not set for this logger. Replacing with DefaultLoggerPrintFunc.")
Expand All @@ -207,6 +205,18 @@ func (l *logger) Doctor() (neededDoctor bool) {
return
}

func (l *logger) printStack(stages []string) {
for i := len(stages) - 1; i >= 0; i-- {
padding := ""
if !l.config.DisableStackIndentation {
for j := 0; j < len(stages)-1-i; j++ {
padding += " "
}
}
l.Printf(" %s%s:%s", padding, regexpCallArgs.FindString(stages[i]), strings.Split(regexpCodeReference.FindString(stages[i]), ":")[1])
}
}

//Printf is the function used to log
func (l *logger) Printf(format string, data ...interface{}) {
l.config.PrintFunc(format, data...)
Expand Down
16 changes: 16 additions & 0 deletions regexp.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"regexp"
"runtime/debug"
"strconv"
"strings"

"github.com/fatih/color"
Expand Down Expand Up @@ -107,3 +108,18 @@ func findFailingLine(lines []string, funcLine int, debugLine int) (failingLineIn

return
}

//parseRef parses reference line from stack trace to extract filepath and line number
func parseRef(refLine string) (string, int) {
ref := strings.Split(regexpCodeReference.FindString(refLine), ":")
if len(ref) != 2 {
panic(fmt.Sprintf("len(ref) > 2;ref='%s';", ref))
}

lineNumber, err := strconv.Atoi(ref[1])
if err != nil {
panic(fmt.Sprintf("cannot parse line number '%s': %s", ref[1], err))
}

return ref[0], lineNumber
}
7 changes: 6 additions & 1 deletion utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ func isIntInSlice(i int, s []int) bool {
return false
}

func deleteBankLinesFromRange(lines []string, start, end *int) {
//deleteBlankLinesFromRange increments and decrements respectively start and end so they are not representing an empty line (in slice lines)
func deleteBlankLinesFromRange(lines []string, start, end *int) {
//clean from out of range values
(*start) = max(*start, 0)
(*end) = min(*end, len(lines)-1)

//clean leading blank lines
for (*start) <= (*end) {
if strings.Trim(lines[(*start)], " \n\t") != "" {
Expand Down

0 comments on commit 5d8938d

Please sign in to comment.