如何在大型Java代码库中查找具有错误类名的记录器?

时间:2017-02-09 09:14:52

标签: regex eclipse grep find negative-lookbehind

在大型代码库中,可能存在错误的记录器初始化,如下所示:

public class MyClass implements Whatever {

    private static final Logger logger = Logger.getLogger(WrongClass.class);

(应该是getLogger(MyClass.class))。我正在寻找一种快速而肮脏的方式来发现它们,而无需编写整个程序。误报,如果不是太多(例如内部类别)是可以接受的。

我在Eclipse中尝试了这个正则表达式搜索,但它与我上面的例子不匹配:

(?s)(?<!class \1.*)Logger.getLogger\((\w+)\.class

我也考虑了一些find -exec grep -q \; -print,但我也没有让它工作。

1 个答案:

答案 0 :(得分:1)

我遇到了同样的挑战,并没有及时获得find / grep / sed / awk等。所以我决定写一个小的Java程序:

public static void main(String[] args) throws IOException {
    Files.walk(Paths.get("/path/to/sources")).filter(p -> p.toFile().isFile() && p.getFileName().toFile().getName().endsWith(".java"))
        .forEach(p -> {
            String filename = p.toFile().getName();
            String clazz = filename.split("\\.")[0];
            try {
                FileUtils.readLines(p.toFile()).forEach(line -> {
                    if (line.contains("getLog(") || line.contains("getLogger(")) {
                        if (line.matches(".*\\([ ]*" + clazz + "\\.class[ ]*\\).*")) {
                            System.out.println(String.format(" ok: %s: %s", p, line.trim()));
                        } else {
                            System.out.println(String.format("nok: %s: %s", p, line.trim()));
                        }
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
  }

显然它很快而且很脏。 ; - )