/
slowg.go
115 lines (106 loc) · 2.49 KB
/
slowg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package slowg
import (
"errors"
"go/ast"
"go/types"
_ "golang.org/x/exp/slog" // require the exp module for the unit tests
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
)
// Analyzer implements an analysis function that checks for inappropriate use
// of Logger.With.
var Analyzer = &analysis.Analyzer{
Name: "slowg",
Doc: "check for inappropriate use of Logger.With()",
URL: "https://github.com/cilium/linters",
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: run,
}
func run(pass *analysis.Pass) (any, error) {
inspect, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
if !ok {
return nil, errors.New("require analyzer of type *inspector.Inspector")
}
nodeFilter := []ast.Node{
(*ast.SelectorExpr)(nil),
}
inspect.Preorder(nodeFilter, func(node ast.Node) {
sel, ok := node.(*ast.SelectorExpr)
if !ok {
return
}
if sel.Sel == nil {
return
}
call, ok := sel.X.(*ast.CallExpr)
if !ok {
return
}
fn := typeutil.StaticCallee(pass.TypesInfo, call)
if fn == nil {
// not a static call
return
}
if !isSlogPkg(fn) {
// not the log/slog or x/exp/slog package
return
}
if recvName(fn) != "Logger" {
// not a receiver of the Logger struct
return
}
switch fn.Name() {
case "With", "WithGroup":
default:
// not one of the call we need to care about
return
}
meth := sel.Sel.Name
if !isLogMethod(meth) {
// not a logging method (e.g. Info, DebugCtx, ...)
return
}
pass.ReportRangef(call, "call to %s on a newly instantiated Logger", meth)
})
return nil, nil
}
func isSlogPkg(fn *types.Func) bool {
switch fn.Pkg().Path() {
case "log/slog":
return true
case "golang.org/x/exp/slog":
return true
}
return false
}
func isLogMethod(s string) bool {
switch s {
case "Log", "LogAttrs",
"Debug", "Info", "Warn", "Error",
"DebugCtx", "InfoCtx", "WarnCtx", "ErrorCtx", // old method names, still used in x/exp/slog
"DebugContext", "InfoContext", "WarnContext", "ErrorContext":
return true
}
return false
}
func recvName(fn *types.Func) string {
sig, ok := fn.Type().(*types.Signature)
if !ok {
return ""
}
recv := sig.Recv()
if recv != nil {
t := recv.Type()
if pt, ok := t.(*types.Pointer); ok {
t = pt.Elem()
}
if nt, ok := t.(*types.Named); ok {
return nt.Obj().Name()
}
}
return ""
}