设置Maven Embedder执行的记录器

时间:2009-10-27 15:55:14

标签: logging maven-2 maven-embedder

我想通过Java代码运行Maven编译。因此,我使用了Maven Embedder的使用示例解释here

这很好用,除了我想将Maven Embedder写的所有日志重定向到我自己的Logger。所以,我创建了自己的MavenEmbedderLoggerout是我的PrintStream):

class MvnLogger extends AbstractMavenEmbedderLogger {

    public void error(String s, Throwable throwable) {
        out.println("[error] " + s);
        print(throwable);
    }

    public void info(String s, Throwable throwable) {
        out.println("[info] " + s);
        print(throwable);
    }

    ...

    public void close() {
    }

    private void print(Throwable t) {
        if (t != null) {
            t.printStackTrace(out);
        }
    }

}

然后,我将此Logger设置为Embedder:

    Configuration config = new DefaultConfiguration();
    config.setUserSettingsFile(new File("..."));
    config.setClassLoader(Thread.currentThread().getContextClassLoader());
    ConfigurationValidationResult validationResult = MavenEmbedder.validateConfiguration(config);
    if (validationResult.isValid()) {
        try {
            MavenEmbedder embedder = new MavenEmbedder(config);
            // SET THE LOGGER
            embedder.setLogger(new MvnLogger());
            MavenExecutionRequest request = new DefaultMavenExecutionRequest();
            request.setBaseDirectory(path);
            request.setGoals(Arrays.asList(new String[] { "clean", "install" }));
            MavenExecutionResult result = embedder.execute(request);
            ...

但是,当我执行此代码时,来自Maven的所有日志都显示在默认的Logger中(在我的例子中,System.out)而不是我的Logger。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

好的,我自己找到了:记录器必须设置为Configuration,而不是MavenEmbedder类:

    Configuration config = new DefaultConfiguration();
    // SET THE LOGGER HERE !
    config.setMavenEmbedderLogger(new MvnLogger());
    config.setUserSettingsFile(new File(...));
    config.setClassLoader(Thread.currentThread().getContextClassLoader());
    ConfigurationValidationResult validationResult = MavenEmbedder.validateConfiguration(config);
    if (validationResult.isValid()) {
        try {
            MavenEmbedder embedder = new MavenEmbedder(config);
            // AND NOT HERE!
            // embedder.setLogger(new MvnLogger());
            MavenExecutionRequest request = new DefaultMavenExecutionRequest();
            request.setBaseDirectory(path);
            request.setGoals(Arrays.asList(new String[] { "clean", "install" }));
            // request.setProperties();
            MavenExecutionResult result = embedder.execute(request);

但是,使用我以前的代码时很奇怪,没有使用Logger代替System.out ......