开发者

Set the logger for a Maven Embedder execution

I want to run a Maven compilation by my Java code. Thus, I've used the example of the usage of Maven Embedder explained here.

This works pretty well, except that I want to redirect all the log written by the Maven Embedder to my own Logger. So, I created my own MavenEmbedderLogger (out is a PrintStream of mine):

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);
        }
    }

}

and then, I've set this Logger to the 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);
            ...

However, when I execute this code, all logs from Maven are displayed in the default Logger (in my case, the System.out) instead of my Logger.

What do I do wrong?


Ok, I just found by myself: The Logger must be set to the Configuration, not the MavenEmbedder class:

    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);

However, that's quite strange that with my previous code, the Logger was not used instead of System.out...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜