0

I am not able to generate log file using log4j2 spring boot 2.4, it's only printing logs in eclipse console. I already tried multiple solutions provided across web like: exclusions, renamed file to log4j2, changed properties multiple times (some are not using log4j.xx and some are not using it) not sure what to do ?

properties file:

log4j.rootLogger=DEBUG, stdout, file
log4j.logger.infoLogger=DEBUG, infoLogger
log4j.additivity.infoLogger = false

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-dd-MM HH:mm:ss,SSS} %-10p [%l] : %m%n

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:/logs/application.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=2
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-10p %l -- %m%n

log4j.appender.infoLogger=org.apache.log4j.RollingFileAppender
log4j.appender.infoLogger.File=C:/logs/applicationInfo.log
log4j.appender.infoLogger.MaxFileSize=10MB
log4j.appender.infoLogger.MaxBackupIndex=2
log4j.appender.infoLogger.layout=org.apache.log4j.PatternLayout
log4j.appender.infoLogger.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} %-10p %l -- %m%n

pom.xml:

    I am doing the exclusions from all spring dependencies, as mention in some solutions.

<dependency>
    <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-log4j2</artifactId>
    </dependency>

Demo Java file:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Controller {
    
        protected final  Logger logger = LogManager.getLogger(Controller.class);
        ....
 }

Friends, Please review and let me know the problem in it. Please do not mark it duplicate as I already tried the solutions available. May be I missed some :)

Hitesh Kumar
  • 512
  • 1
  • 8
  • 27
  • The issue is I am not using application.properties and if possible I need solution without it – Hitesh Kumar Jun 12 '21 at 18:44
  • I am using system property appender.email.SMTPHost=${sys:log4j.smtpHost} but it is not loading from context.xml and reading host as ${sys:log4j.smtpHost} – Hitesh Kumar Jun 17 '21 at 19:05

3 Answers3

2

Following is a working example for log4j2 integration with Spring boot. Tried with Gradle build but can be used for maven build too.

Points to be considered(if you are using spring boot):

  1. Remove Spring default logging modules from all the configuration modules
  2. Add log4j2 starter for spring boot
  3. Inform spring about log4j2 config file by adding value to the property logging.config=
  4. Make sure log4j2 config is proper as per documentations (else logging will not work as expected)

Project config:

build.gradle

plugins {
    id 'org.springframework.boot' version '2.5.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'idea'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web')
    implementation('org.springframework.boot:spring-boot-starter') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
    implementation('org.springframework.boot:spring-boot-starter-log4j2')

    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

configurations {
    all {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
}

log4j.properties

rootLogger.level = INFO
property.filename = application.log
appenders = R, console

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d %5p [%t] (%F:%L) - %m%n

appender.R.type = RollingFile
appender.R.name = File
appender.R.fileName = ${filename}
appender.R.filePattern = ${filename}.%d{yyyy-MM-dd}
appender.R.layout.type = PatternLayout
appender.R.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
appender.R.policies.type = Policies
appender.R.policies.time.type = TimeBasedTriggeringPolicy
appender.R.policies.time.interval = 1

rootLogger.appenderRefs = R, console

rootLogger.appenderRef.console.ref = STDOUT
rootLogger.appenderRef.R.ref = File

application.properties

logging.config=classpath:log4j2.properties

AppController.java

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@RestController
public class AppController {

private static final Logger LOG = LogManager.getLogger(AppController.class);
    @RequestMapping(value = "/refresh_configs", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> refreshConfig() {
        LOG.info("refresh_configs");
        return new ResponseEntity<>("OK", HttpStatus.OK);
    }
}

application.log

2021-06-12 22:39:00 HelperApplication [INFO] Starting HelperApplication using Java 11.0.9 on 88e9fe567a24 with PID 66713 (/Users/${USER}/Desktop/Helper/out/production/classes started by ${USER} in /Users/${USER}/Desktop/Helper)
2021-06-12 22:39:00 HelperApplication [INFO] No active profile set, falling back to default profiles: default
2021-06-12 22:39:01 TomcatWebServer [INFO] Tomcat initialized with port(s): 8080 (http)
2021-06-12 22:39:01 Http11NioProtocol [INFO] Initializing ProtocolHandler ["http-nio-8080"]
2021-06-12 22:39:01 StandardService [INFO] Starting service [Tomcat]
2021-06-12 22:39:01 StandardEngine [INFO] Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-06-12 22:39:01 [/] [INFO] Initializing Spring embedded WebApplicationContext
2021-06-12 22:39:01 ServletWebServerApplicationContext [INFO] Root WebApplicationContext: initialization completed in 580 ms
2021-06-12 22:39:01 Http11NioProtocol [INFO] Starting ProtocolHandler ["http-nio-8080"]
2021-06-12 22:39:01 TomcatWebServer [INFO] Tomcat started on port(s): 8080 (http) with context path ''
2021-06-12 22:39:01 HelperApplication [INFO] Started HelperApplication in 1.187 seconds (JVM running for 1.944)
2021-06-12 22:39:01 ApplicationAvailabilityBean [INFO] Application availability state LivenessState changed to CORRECT
2021-06-12 22:39:01 ApplicationAvailabilityBean [INFO] Application availability state ReadinessState changed to ACCEPTING_TRAFFIC
2021-06-12 22:39:17 [/] [INFO] Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-06-12 22:39:17 DispatcherServlet [INFO] Initializing Servlet 'dispatcherServlet'
2021-06-12 22:39:17 DispatcherServlet [INFO] Completed initialization in 0 ms
2021-06-12 22:39:17 AppController [INFO] refresh_configs
2021-06-12 22:49:33 AppController [INFO] refresh_configs
2021-06-12 23:01:52 ApplicationAvailabilityBean [INFO] Application availability state ReadinessState changed from ACCEPTING_TRAFFIC to REFUSING_TRAFFIC

Ref:
https://stackoverflow.com/a/39703897/2987755

https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/howto-logging.html#howto-configure-log4j-for-logging

dkb
  • 4,389
  • 4
  • 36
  • 54
0

Try changing the file path to another directory. Sometimes there are some permission issues for C drive.

Fahim Fahad
  • 61
  • 1
  • 2
  • 4
0

You are using the spring boot dependency for log4j2. The syntax of the properties file is different to log4j. That's why no log file will be created. You have to migrate your properties, see Migrating from log4j to log4j2 - properties file configuration

Thilo Schwarz
  • 640
  • 5
  • 24
  • I tried bro but not working. not generating files – Hitesh Kumar Jun 12 '21 at 14:51
  • You can start log4j2 in trace mode to see exactly what happens. That's a nice way to find out problems. But I don't know it for properties syntax, sorry. For xml it would be ``. – Thilo Schwarz Jun 12 '21 at 15:32
  • Found it for properties syntax. Just set `status = trace` in your log4j2.properies. – Thilo Schwarz Jun 12 '21 at 15:53
  • I changed it to Trace but didn't get anything extra. Trace is a log level used to log the application messages. You are in the right path, we have to debug it and find where it is failing. Thanks – Hitesh Kumar Jun 12 '21 at 16:05