views:

258

answers:

1

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?

+1  A: 

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...

romaintaz