Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j seems not to work in Spring Boot

I tried to add Spring and Maven to one of my existing project, and I find that no matter how I configure, the logging seems to be out of my control.

I tried putting the log4j.properties in src/main/java and src/main/resources(Actually I am not sure where to put).

But when I use Log4j to log, the log displays in the console only, though I configure it into a file.

My log4j.properties is like:

log4j.rootLogger=DEBUG, A1 
log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.encoding=utf-8
log4j.appender.A1.File=E:\Programminglog\debug.log 
log4j.appender.A1.Threshold = DEBUG 
log4j.appender.A1.Append=true
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

I am not sure if I miss something or Spring overrides some settings, since I am new to Maven and Spring.

PS: Before I add dependencies of Log4j in pom.xml,no compile errors though I use org.apache.log4j.Logger

This is how my application.java looks like:

@Configuration
@EnableAutoConfiguration
@ComponentScan({"hello","wodinow.weixin.jaskey"})
public class Application extends WebMvcConfigurerAdapter  {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

        LogUtil.info("Application Boots!");// here this line does not show in the file
    }

    @Bean
    public CommandService commandService(){
        return CommandService.getInstance();
    }
}

enter image description here

like image 867
JaskeyLam Avatar asked Oct 28 '14 13:10

JaskeyLam


1 Answers

If you are using log4j with spring-boot then you have to add dependency with "exclusions" in your pom.xml

 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>1.3.3.RELEASE</version>
  **<exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>**
</dependency>

**<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j</artifactId>
  <version>1.2.5.RELEASE</version>
</dependency>**

Please follow this. It will resolve your problem.

http://www.atechref.com/blog/maven/spring-boot-using-log4j-logging/

like image 141
Rahul sharma Avatar answered Oct 11 '22 14:10

Rahul sharma