log4j example in springboot – JavaDream

Home / log4j example in springboot – JavaDream

In this post we will see how to use log4j in java or spring boot . Logging is a most important feature that we use to detect if any error occurs or not .

Spring boot by default provides slf4j logging in spring boot. For Using slf4j logging we have to include only web starter dependency.

Logging plays a important role while we debug our application on server. using log4j in java is very important. So try to make as simple as possible so anybody can understand about the issue after seeing your logs.

In this post we will see how to use Apache Log4j in spring boot application. To use Apache Log4j we have to follow below steps.

1- Add below dependency in your pom.xml file or get this from maven Repositry to enable log4j in java
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.16</version>
</dependency>
2- create a properties file with name log4j.properties in your project resource folder and add below lines .

For Linux Server:

log4j.rootCategory=INFO, A1

log4j.appender.A1=org.apache.log4j.FileAppender

log4j.appender.A1.File=/var/log/data.log

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%d{DATE} %F|%L : %m%n

For Window Console or your Eclipse Console make below entry in your log4j.properties :

pattern=%d %5p [%24t] %32c{2}|%L - %m%n
log4j.rootLogger=DEBUG, Console, Appender1

# console is set to be a ConsoleAppender.
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=${pattern}
log4j.appender.Console.Threshold=info

# Define the file appender
log4j.appender.Appender1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.Appender1.File=/var/log/R2faSupportNew.log

#log4j.appender.Appender1.File=${catalina.home}/logs/revesecure_api.log
log4j.appender.Appender1.DatePattern='.'yyyy-MM-dd

# Set the append to false, should not overwrite
log4j.appender.Appender1.Append=true

# Set the threshold to debug mode
log4j.appender.Appender1.Threshold=info

# Define the layout for file appender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout

log4j.appender.Appender1.layout.conversionPattern=${pattern}
3- Now go to your class and initialize the Logger object like below
private static final Logger logger = Logger.getLogger(CalculateSMSCost.class.getName());
4- Now go to your java class and print your logs like below.
logger.info("Apache log4j logging Example");
Now run your application and see the logs on console.

You may also like:

File Upload in Spring Boot

Spring boot security using JWT ( JSON WEB TOKENS ).

Actuator in spring boot for monitoring application

Help Others, Please Share

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

x