Kevin Chadwick
unread,Jun 9, 2020, 3:05:48 PM6/9/20Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to golang-nuts
BSD license/public domain, Feel free to criticise/use
Means I can easily disable file/line inclusion if stdlib ever gets
that part of the error values proposal. Also easy to apply with
search/replace.
// LogPrint : An error wrapping log.Print replacement that adds location and
// file info to each link in the chain, without adding LOC.
// It utilises fmt.Errorf %w to create/preserve the original errors
// testing Operand.
//
// @ARGS :
/// testErr = nil, or an error type (any comparison operands will be preserved or applied)
// prepend = fmt.Sprint arguments to form a string that is prepended (any comparison operands will be lost)
//
// @RETURN :
// error with log Lshortfile equivalents prepended and optional test operands applied (Errorf Unwrap method)
//
// @NOTE :
// Any standard lib changes can be accommodated for by modifying
// this function
//
// Every chain should still be logged to avoid loss upon fatal exception.
// Wrapping simply preserves a self contained log chain line output plus
// any embedded operand for later errors.(As|Is) test cases...
func LogPrint(testErr error, prepend ...interface{}) error {
// Get the Location of this functions caller
_, fileName, fileLine, ok := runtime.Caller(1)
fileName = filepath.Base(fileName)
var s string
if ok == true {
s = fmt.Sprintf("%s:%d", fileName, fileLine)
} else {
s = "LogPrint: runtime.Caller(): failed"
}
// Accept arguments or interface just like fmt.Sprint
text := fmt.Sprint(prepend...)
// Only include an unwrap method when the user requests it.
if testErr != nil {
testErr = fmt.Errorf("%v: %v: %w: ", s, text, testErr)
} else {
testErr = fmt.Errorf("%v: %v: ", s, text)
}
log.Print(testErr.Error())
return testErr
}