2016-07-29 62 views
0

我创建了一个使用mojo-executor运行另一个Mojo的majo Mojo。当这个得到执行时,该Mojo执行的输出将进入默认输出。所以,当它得到执行,它将打印如下:如何拦截maven插件生成日志

[INFO] Compiling 1 source file to /Users/sergio/hello-world/target/classes 
[INFO] 
[INFO] --- utqg-maven-plugin:1.1.0-SNAPSHOT:errorprone (default) @ my-app --- 
/Users/sergio/hello-world/src/test/java/com/mycompany/App2Test.java:30: warning: [UTQG:HelperMethodCannotBePublic] Helper Methods of test classes cannot be public. 
    public String getName() { 
       ^
    (see https://www.mycompany.com/utqg/HelperMethodCannotBePublic) 
/Users/sergio/hello-world/src/test/java/com/mycompany/service/MyServiceTest.java:14: warning: [UTQG:HelperMethodCannotBePublic] Helper Methods of test classes cannot be public. 
    public void myHelperMethod(){ 
      ^
    (see https://www.mycompany.com/utqg/HelperMethodCannotBePublic) 
/Users/sergio/hello-world/src/test/java/com/mycompany/service/MyServiceTest.java:170: warning: [UTQG:E:UseDeprecatedStatementsNotAllowed] Usage of Deprecated Classes, Methods or Variables Not Allowed 
    final URL url = new File(".").toURL(); 
            ^
    (see https://www.mycompany.com/utqg/HelperMethodCannotBePublic) 
Note: /Users/sergio/hello-world/src/test/java/com/mycompany/service/MyServiceTest.java uses or overrides a deprecated API. 
Note: Recompile with -Xlint:deprecation for details. 
3 warnings 

好了,所有那些警告预料的,因为我已经创造了一些bugcheckers与容易出错。但问题是我必须从标准输出中移除这个输出并将其放入一个文件中。但只有那一部分。

什么我试过到目前为止是我的输出重定向到一个文件时,它得到执行:

PrintStream originalStream = System.out; 
    try { 
     PrintStream ps = new PrintStream(new FileOutputStream(ERRORPRONE_FILE, false)); 
     System.setOut(ps); 
    } catch (FileNotFoundException e){ 
     LOGGER.error("ErrorProneRunMojo", e); 
     throw new MojoExecutionException(e.getMessage()); 
    } 
    // do my logic of calling the plugin here 
    System.out.flush(); 
    System.setOut(originalStream); 

物业: - 我不能使用mvn --logFile-l因为他们删除一切从标准输出和将它放在文件中,解决方案也不应该由用户放置一个--logFile或类似的东西来保证。

+1

我认为设置系统标准输出和错误流是唯一的方法。你有没有遇到这个问题? – Tunaki

+0

是的,它仍然没有得到正确的字符串。它在执行完后得到所有字符串。但我检查了代码,它没问题。 –

+0

MavenProject包含您可能需要为记录器的不同实例进行查找的记录器,或者根据您如何调用其他mojo来设置自己的记录器实例?但是如果没有具体的代码,很难提供帮助......此外,它看起来不会使用记录器在您的mojo中创建输出? – khmarbaise

回答

0

好吧,我已经试过两种方法及二者的工作:

  • 创建一个ASM代理拦截器,拦截所有输入PrintStream.print(),但太硬,是难以控制的结果。您可以在ASM指南中查看如何执行此操作,http://download.forge.objectweb.org/asm/asm4-guide.pdf

  • 另一种选择是重新分配System.out和System.err。因为我们可以管理Maven的目标,所以它更容易实现,并且可以更好地控制结果。