While running javac Main.java
command I get a package org.apache.log4j does not exist
error.
Main
class
public class Main {
private static Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) {
BasicConfigurator.configure();
logger.info("in Main class");
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>example</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
log4j.properties
log4j.rootCategory=debug,console
log4j.logger.com.demo.package=debug,console
log4j.additivity.com.demo.package=false
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.out
log4j.appender.console.immediateFlush=true
log4j.appender.console.encoding=UTF-8
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d [%t] %-5p %c - %m%n
Error message I get is:
Looks like you're missing import
statements in your Main
class.
Try this:
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
public class Main {
private static Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) {
BasicConfigurator.configure();
logger.info("in Main class");
}
}
You're running the compilation not with maven but with command-line javac
. Without Maven, you don't have dependencies automatically added to your classpath.
In this case, you have to add log4j to your classpath.
It will look like this (running from the sources directory, which is <project_root>\src\main\java
in the default maven layout:
javac company/Main.java -cp %userprofile%\.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar
I assume that your local Maven repo is in the default Windows path %userprofile%\.m2
. If it is in some other part (or Linux), you have to change the path to your log4j-1.2.17.jar
.
In this case, the class Main.class
will be compiled into the same package where Main.class
is.
Just run mvn compile
from the directory where your pom.xml
is.
Note that maven will compile classes into the target
directory, i.e. your compiled class will be in path like \target\classes\company\Main.class
(relative to your project root, where your pom.xml
is).