0

I have a maven java project using log4j2 2.5 (NOT log4j version 1.x).

I have read a lot of posts here regarding my issue but nothing works for me, so please, could someone help me?

I am using log4j2 in the following way:

1) Import package in each of my classes:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

2) For each class, immediately after class line I create a logger:

public class A {

    // log4j2 logger
    private static final Logger logger = LogManager.getLogger(Main.class.getName());

}

3) Once I have created the logger as step 2, I use it as normal:

    logger.trace("some message");
    logger.info("another message");

I have put log4j2.xml file in src\main\resources (this folder is in the class-path):

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Properties>
        <Property name="LOG_DIR">.</Property>
        <Property name="ARCHIVE">output.log</Property>
        <Property name="CONSOLE_PATTERN">[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</Property>
        <Property name="FILE_PATTERN">%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${CONSOLE_PATTERN}"/>
        </Console>
        <File name="file" fileName="${LOG_DIR}/${ARCHIVE}" immediateFlush="false" append="false">
            <PatternLayout pattern="${FILE_PATTERN}"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO" additivity="false">
            <AppenderRef ref="console"/>
            <AppenderRef ref="file"/>
        </Root>
        <Logger name="com.distributed.analyzer" level="TRACE" additivity="false">
            <AppenderRef ref="console"/>
            <AppenderRef ref="file"/>
        </Logger>
        <Logger name="com.distributed.analyzer.errors" level="ERROR" additivity="false">
            <AppenderRef ref="console"/>
            <AppenderRef ref="file"/>        
        </Logger>
    </Loggers>
</Configuration>

Regarding maven, I have put below log4j2 dependencies for maven:

log4j-api-2.5.jar
log4j-core-2.5.jar

in pom.xml file I specify as below:

 <dependencies>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.5</version>
    </dependency>   

From eclipse, I can build the project without problems (without errors) and I can execute it as well. All correct.

So right now what I am trying to do is to obtain a runnable jar file in order to I can execute using below command line:

java -jar myapp.jar

So in order to build it in a simple way I use maven-shade-plugin and I specify it in my pom.xml as follows:

<plugins>           
    <!-- Maven Shade Plugin -->
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.4.3</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.distributed.analyzer.Main</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
  </plugin>
</plugins>

So I build it using below goals: compile package

JAR file is correctly created but when I launch it from command line using:

java -jar myapp.jar

below error message is shown (seems like log4j2 is not found... I do not understand):

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/logging/log4j/LogManager
        at com.distributed.analyzer.Main.<clinit>(Main.java:22)
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.LogManager

        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more

When running the program in eclipse everything work fine, but when I package it with maven and try to run the jar I get this kind of error....

UPDATED: If I create the runnable jar using export option from eclipse and the checking: "Package required libraries into the generated JAR" then the JAR package is created correctly. It contains all jar files in the root and a folder resources with all the resources but If I execute again using:

java -jar myapp.jar

I continue getting similar error:

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
Willy
  • 9,848
  • 22
  • 141
  • 284
  • Looks like you set a wrong setting in building jar. You should pack libraries with the jar –  Feb 13 '16 at 04:38
  • You need to make sure you're including the dependencies with the jar, either as a all in on jar [like this](http://stackoverflow.com/questions/1729054/including-dependencies-in-a-jar-with-maven) or include the dependency jars [like this](http://stackoverflow.com/questions/3558459/maven-packaging-dependencies-alongside-project-jar) – MadProgrammer Feb 13 '16 at 04:38
  • @MadProgrammer I thought that maven-shade-plugin does it as well... or not? – Willy Feb 13 '16 at 04:44
  • @AnthonyLaw So is it not correct the goals compile and package? which ones are the correct? – Willy Feb 13 '16 at 04:45
  • @user1624552 Not 100% sure, I've set up a series of "base" configuration for all my projects which I use, so I don't tend to do this a lot (I prefer copy along rather than fat jar, but that's me) – MadProgrammer Feb 13 '16 at 04:45
  • If you are using Eclipse, when you export the jar, there is 3 options at the bottom. http://archive.eclipse.org/eclipse/downloads/drops/R-3.5-200906111540/images/runnable-jar-in-jar-export.png –  Feb 13 '16 at 04:48
  • @AnthonyLaw Yes, I tried that as well, but I continue getting a similar error, see my updated post at the end. – Willy Feb 13 '16 at 04:58
  • See documentation. Looks like you are missing a configuration file to be embedded with log4j –  Feb 13 '16 at 04:59
  • @AnthonyLaw As far as I know, and what I have read is that for using log4j2 you require to have log4j2.xml file correctly configured and placed in the class-path (in my case src\main\resources). Resources and log4j2.xml are included in the jar so I do not understand why it cannot be found.... – Willy Feb 13 '16 at 05:11
  • @user1624552 Instead using its automatic configuration, try using `System.setProperty("log4j.configurationFile", "/src/main/resources/log4j2.xml")` –  Feb 13 '16 at 05:25
  • @AnthonyLaw I works well if I execute from eclipse but if I execute it from jar file it continues throwing the same error: ERROR StatusLogger No log4j2 configuration file found. Using default configurati on: logging only errors to the console. – Willy Feb 13 '16 at 05:34
  • @user1624552 Try this? `Class.class.getClassLoader().getResource("log4j2.xml")` It returns a URI –  Feb 13 '16 at 05:36
  • I have found the solution, problem was that first line after class was incorrect, that is, replacing: private static final Logger logger = LogManager.getLogger(Main.class.getName()); by private static final Logger logger = LogManager.getLogger(Main.class); works! ;) but it works if I export in eclipse using second option "Package required libraries..." instead of "Extract required libraries...". This last option does not work and to make this last option to work I need to copy log4j2.xml in the root of the jar, and then works as well. – Willy Feb 13 '16 at 05:55
  • I have the same problem too. –  Feb 13 '16 at 06:28
  • But using "Package required libraries...", I can't even open the jar. It laggs –  Feb 13 '16 at 06:35

0 Answers0