Skip to content
This repository has been archived by the owner on Sep 27, 2024. It is now read-only.

Add gplog.FatalNoPanicLogStacktrace() #69

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions gplog/gplog.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ const (
* cannot be reached. This function will exit the program after printing
* the error message.
* - FatalWithoutPanic: Same as Fatal, but will not trigger panic. Just exit(1).
* - FatalWithoutPanicLogStacktrace(): Same as FatalWithoutPanic, but
* writes the stacktrace into the log file for debug purpose.
*/
type LogPrefixFunc func(string) string
type LogFileNameFunc func(string, string) string
Expand Down Expand Up @@ -324,6 +326,37 @@ func FatalWithoutPanic(s string, v ...interface{}) {
exitFunc()
}

func FatalWithoutPanicLogStacktrace(err error, output ...string){
if err != nil {
var outputStr string
if len(output) == 0 {
outputStr = ""
} else {
outputStr = output[0]
}
logMutex.Lock()
defer logMutex.Unlock()
message := GetLogPrefix("CRITICAL")
errorCode = 2
stackTraceStr := ""
if err != nil {
message += fmt.Sprintf("%v", err)
stackTraceStr = formatStackTrace(errors.WithStack(err))
if outputStr != "" {
message += ": "
}
}
message += strings.TrimSpace(fmt.Sprintf(outputStr))
_ = logger.logFile.Output(1, message+stackTraceStr)
if logger.shellVerbosity >= LOGVERBOSE {
_ = logger.logStderr.Output(1, message + stackTraceStr)
} else {
_ = logger.logStderr.Output(1,message)
}
exitFunc()
}
}

type stackTracer interface {
StackTrace() errors.StackTrace
}
Expand Down
17 changes: 17 additions & 0 deletions gplog/gplog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,23 @@ var _ = Describe("logger/log tests", func() {
testhelper.ExpectRegexp(logfile, fatalExpected+expectedMessage)
})
})
Context("FatalWithoutPanicLogStacktrace", func() {
It("prints to the log file with stack trace, then exit(1)", func() {
gplog.SetExitFunc(func() {})
expectedMessage := "logfile error something wrong"
err := errors.WithStack(errors.New(expectedMessage))
expectedWithStack := `.*\[CRITICAL\]:-logfile error something wrong
.*gplog_test\.glob.*
.*gplog_test\.go.*
.*
.*internal\/suite.go.*
runtime\.goexit.*`
gplog.FatalWithoutPanicLogStacktrace(err, "")
testhelper.NotExpectRegexp(stdout, fatalExpected+expectedMessage)
testhelper.ExpectRegexp(stderr, fatalExpected+expectedMessage)
Expect(string(logfile.Contents())).To(MatchRegexp(expectedWithStack))
})
})
})
})
})