-
Notifications
You must be signed in to change notification settings - Fork 58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
🐛 Fix: Prevent nil errors in log.Error to ensure proper logging and add sanity check and add custom linter to avoid this scenario in the future #1599
Open
camilamacedo86
wants to merge
3
commits into
operator-framework:main
Choose a base branch
from
camilamacedo86:fix-error-message
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+174
−17
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
1601df7
Add custom Linter to not allow improper usage of logger.Error(nil, ..…
camilamacedo86 a33832b
Fix: Prevent nil errors in setupLog.Error to ensure proper logging
camilamacedo86 5a41f9f
Fixes improper usage of log.Error(nil,..) scenarios for EventHandler
camilamacedo86 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
package analyzers | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"go/ast" | ||
"go/format" | ||
"go/token" | ||
"go/types" | ||
|
||
"golang.org/x/tools/go/analysis" | ||
) | ||
|
||
var SetupLogNilErrorCheck = &analysis.Analyzer{ | ||
Name: "setuplognilerrorcheck", | ||
Doc: "Detects improper usage of logger.Error() calls, ensuring the first argument is a non-nil error.", | ||
Run: runSetupLogNilErrorCheck, | ||
} | ||
|
||
func runSetupLogNilErrorCheck(pass *analysis.Pass) (interface{}, error) { | ||
for _, f := range pass.Files { | ||
ast.Inspect(f, func(n ast.Node) bool { | ||
callExpr, ok := n.(*ast.CallExpr) | ||
if !ok { | ||
return true | ||
} | ||
|
||
// Ensure function being called is logger.Error | ||
selectorExpr, ok := callExpr.Fun.(*ast.SelectorExpr) | ||
if !ok || selectorExpr.Sel.Name != "Error" { | ||
return true | ||
} | ||
|
||
// Ensure receiver (logger) is identified | ||
ident, ok := selectorExpr.X.(*ast.Ident) | ||
if !ok { | ||
return true | ||
} | ||
|
||
// Verify if the receiver is logr.Logger | ||
obj := pass.TypesInfo.ObjectOf(ident) | ||
if obj == nil { | ||
return true | ||
} | ||
|
||
named, ok := obj.Type().(*types.Named) | ||
if !ok || named.Obj().Pkg() == nil || named.Obj().Pkg().Path() != "github.com/go-logr/logr" || named.Obj().Name() != "Logger" { | ||
return true | ||
} | ||
|
||
if len(callExpr.Args) == 0 { | ||
return true | ||
} | ||
|
||
// Check if the first argument of the error log is nil | ||
firstArg, ok := callExpr.Args[0].(*ast.Ident) | ||
if !ok || firstArg.Name != "nil" { | ||
return true | ||
} | ||
|
||
// Extract error message for the suggestion | ||
suggestedError := "errors.New(\"kind error (i.e. configuration error)\")" | ||
suggestedMessage := "\"error message describing the failed operation\"" | ||
|
||
if len(callExpr.Args) > 1 { | ||
if msgArg, ok := callExpr.Args[1].(*ast.BasicLit); ok && msgArg.Kind == token.STRING { | ||
suggestedMessage = msgArg.Value | ||
} | ||
} | ||
|
||
// Get the actual source code line where the issue occurs | ||
var srcBuffer bytes.Buffer | ||
if err := format.Node(&srcBuffer, pass.Fset, callExpr); err == nil { | ||
sourceLine := srcBuffer.String() | ||
pass.Reportf(callExpr.Pos(), | ||
"Incorrect usage of 'logger.Error(nil, ...)'. The first argument must be a non-nil 'error'. "+ | ||
"Passing 'nil' results in silent failures, making debugging harder.\n\n"+ | ||
"\U0001F41B **What is wrong?**\n"+ | ||
fmt.Sprintf(" %s\n\n", sourceLine)+ | ||
"\U0001F4A1 **How to solve? Return the error, i.e.:**\n"+ | ||
fmt.Sprintf(" logger.Error(%s, %s, \"key\", value)\n\n", suggestedError, suggestedMessage)) | ||
} | ||
|
||
return true | ||
}) | ||
} | ||
return nil, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package main | ||
|
||
import ( | ||
"github.com/operator-framework/operator-controller/hack/ci/custom-linters/analyzers" | ||
"golang.org/x/tools/go/analysis" | ||
"golang.org/x/tools/go/analysis/unitchecker" | ||
) | ||
|
||
// Define the custom Linters implemented in the project | ||
var customLinters = []*analysis.Analyzer{ | ||
analyzers.SetupLogNilErrorCheck, | ||
} | ||
|
||
func main() { | ||
unitchecker.Main(customLinters...) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
module github.com/operator-framework/operator-controller/hack/ci/custom-linters | ||
|
||
go 1.23.4 | ||
|
||
require golang.org/x/tools v0.29.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= | ||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= | ||
golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= | ||
golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= | ||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= | ||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= | ||
golang.org/x/tools v0.29.0 h1:Xx0h3TtM9rzQpQuR4dKLrdglAmCEN5Oi+P74JdhdzXE= | ||
golang.org/x/tools v0.29.0/go.mod h1:KMQVMRsVxU6nHCFXrBPhDB8XncLNLM0lIy/F14RP588= |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@joelanford you suggested
go build ./hack/ci/custom-linters/cmd/ -o ./bin/custom-linter
But it does not work.
I am missing something silly here.
but anyway that does not seems to be a big deal.