Could Not Read Configuration File From Url [file://log4j.properties
Apache Log4j 2 is a successor of Log4j one.x (who would accept guessed? :p).
Log4j 2 provides a significant comeback in performance compared to its predecessor. It contains asynchronous loggers and supports multiple APIs including SLF4J, commons logging, and java.util.loggging.
In this article, you'll learn how to integrate and configure Log4j 2 in Leap Boot applications. You'll configure different types of appenders including RollingFileAppender
and SMTPAppender
. Yous'll also learn how to use Async logging capabilities provided by Log4j 2.
The idea is to build a simple Spring Boot application from scratch and demonstrate how to get about integrating and configuring Log4j 2 in the app.
So, Permit's become started!
Creating the Project
Let'southward use Spring Boot CLI to generate the project. If you don't have Jump Boot CLI installed, I highly encourage you to exercise so. Bank check out the Official Spring Kick documentation for any help with the installation.
Burn upwardly your final and blazon the post-obit control to generate the project -
spring init --proper noun=log4j2-demo --dependencies=web log4j2-demo
Once the projection is generated, import it into your favorite IDE. The project'south directory construction should look like this -
Adding Log4j2
All the Bound Kick starters depend on spring-boot-starter-logging
, which uses Logback by default. For using Log4j2, you need to exclude spring-boot-starter-logging
and add spring-boot-starter-log4j2
dependency.
Open pom.xml
file and add the post-obit snippet to the <dependencies>
section -
<!-- Exclude Spring Kicking's Default Logging --> <dependency > <groupId > org.springframework.boot </groupId > <artifactId > spring-kicking-starter </artifactId > <exclusions > <exclusion > <groupId > org.springframework.kicking </groupId > <artifactId > spring-boot-starter-logging </artifactId > </exclusion > </exclusions > </dependency > <!-- Add Log4j2 Dependency --> <dependency > <groupId > org.springframework.kicking </groupId > <artifactId > spring-kick-starter-log4j2 </artifactId > </dependency >
Configuring Log4j2
Spring Kicking automatically configures Log4j if it finds a file named log4j2.xml
or log4j2.json
or log4j2.yaml
in the classpath.
In this article, we'll configure log4j 2 using XML. Create a new file log4j2.xml
inside src/primary/resource
directory, and add the following configuration to it -
<?xml version="1.0" encoding="UTF-eight"?> <Configuration status = "WARN" monitorInterval = "30" > <Backdrop > <Belongings proper noun = "LOG_PATTERN" > %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-forty.40c{ane.} : %k%northward%ex </Property > </Properties > <Appenders > <Panel name = "ConsoleAppender" target = "SYSTEM_OUT" follow = "true" > <PatternLayout pattern = "${LOG_PATTERN}" /> </Panel > </Appenders > <Loggers > <Logger proper noun = "com.example.log4j2demo" level = "debug" additivity = "false" > <AppenderRef ref = "ConsoleAppender" /> </Logger > <Root level = "info" > <AppenderRef ref = "ConsoleAppender" /> </Root > </Loggers > </Configuration >
The above configuration defines a simple ConsoleAppender and declares two loggers - an awarding specific logger and the the root logger.
Using Log4j two in the app
Permit's add some logging code to check our logger configuration. Open Log4j2DemoApplication.coffee
and replace it with the post-obit code -
packet com.case.log4j2demo ; import org.apache.logging.log4j. LogManager ; import org.apache.logging.log4j. Logger ; import org.springframework.boot. ApplicationArguments ; import org.springframework.boot. ApplicationRunner ; import org.springframework.boot. SpringApplication ; import org.springframework.kicking.autoconfigure. SpringBootApplication ; @SpringBootApplication public class Log4j2DemoApplication implements ApplicationRunner { private static last Logger logger = LogManager . getLogger ( Log4j2DemoApplication . class ) ; public static void main ( String [ ] args) { SpringApplication . run ( Log4j2DemoApplication . form , args) ; } @Override public void run ( ApplicationArguments applicationArguments) throws Exception { logger. debug ( "Debugging log" ) ; logger. info ( "Info log" ) ; logger. warn ( "Hey, This is a alarm!" ) ; logger. mistake ( "Oops! We have an Mistake. OK" ) ; logger. fatal ( "Damn! Fatal error. Delight fix me." ) ; } }
Nosotros have added 5 uncomplicated logs of different log levels. When you run the app, it logs everything on the console.
Adding a Rolling File Appender
If you want your logs to be written to a file, then y'all can utilise a RollingFile appender. RollingFile appender creates a new file whenever the log file reaches a sure threshold specified by the triggering policy.
It stores the old log files with names matching the pattern specified by the filePattern
parameter -
<!-- Rolling File Appender --> <RollingFile proper name = "FileAppender" fileName = "logs/log4j2-demo.log" filePattern = "logs/log4j2-demo-%d{yyyy-MM-dd}-%i.log" > <PatternLayout > <Blueprint > ${LOG_PATTERN} </Pattern > </PatternLayout > <Policies > <SizeBasedTriggeringPolicy size = "10MB" /> </Policies > <DefaultRolloverStrategy max = "x" /> </RollingFile >
In the to a higher place RollingFile
configuration, I've specified a SizeBasedTriggeringPolicy
which volition roll files over when the size reaches 10MB. The <DefaultRollOverStrategy max="ten" />
element specifies the maximum number of log files that will be kept.
There is another mutual triggering policy called TimeBasedTriggeringPolicy
which is used normally in Log4j2. You tin employ TimeBasedTriggeringPolicy
to specify how often a rollover should occur based on the virtually specific time unit in the date/time pattern specified in the filePattern
attribute.
Here is how you can utilise the TimeBasedTriggeringPolicy
in the in a higher place example to roll files over every day -
<Policies > <TimeBasedTriggeringPolicy interval = "i" /> </Policies >
The interval
attribute specifies the frequency of rollover. So if y'all want to curlicue files over every week, you can specify interval="7"
.
In the above example, the date/time pattern of the file is {yyy-MM-dd}
, where the nigh specific time unit is dd
(engagement). Therefore the TimeBasedTriggeringPolicy
roll files over based on date. If the engagement/time pattern was yyy-MM-dd-HH
, the rollover would occur based on hr.
Finally, To apply the RollingFile
appender, you need to add the above RollingFile
configuration to the <Appenders>
section within log4j2.xml
, and configure one of your loggers to use it like so -
<Root level = "info" > <AppenderRef ref = "ConsoleAppender" /> <AppenderRef ref = "FileAppender" /> </Root >
Adding an SMTP Appender
SMTP appender is very useful in product systems when you want to exist notified about whatever errors in your application via email.
You tin can configure an SMTP appender to send Fault emails to you lot using an SMTP server like and so -
<!-- SMTP Appender --> <SMTP name = "MailAppender" discipline = "Log4j2 Demo [PROD]" to = "youremail@example.com" from = "log4j2-demo-alerts@example.com" smtpHost = "yourSMTPHost" smtpPort = "587" smtpUsername = "yourSMTPUsername" smtpPassword = "yourSMTPPassword" bufferSize = "1" > <ThresholdFilter level = "Fault" onMatch = "Accept" onMismatch = "DENY" /> <PatternLayout > <Pattern > ${LOG_PATTERN} </Pattern > </PatternLayout > </SMTP >
Note that, for SMTP appender to work, you need to include spring-boot-starter-mail
dependency to your pom.xml
file -
<!-- Needed for SMTP appender --> <dependency > <groupId > org.springframework.boot </groupId > <artifactId > spring-kick-starter-postal service </artifactId > </dependency >
Asynchronous Logging
Log4j2 Supports Async loggers. These loggers provide a drastic improvement in performance compared to their synchronous counterparts.
Async Loggers internally use a library called Disruptor for asynchronous logging.
We need to include Disruptor dependency for using async loggers. Add the post-obit to your pom.xml
file -
<!-- Needed for Async Logging with Log4j two --> <dependency > <groupId > com.lmax </groupId > <artifactId > disruptor </artifactId > <version > 3.3.6 </version > </dependency >
Now you tin either brand all Loggers asynchronous, or create a mix of sync and async loggers.
1. Making all Loggers Asynchronous
Making all loggers asynchronous is very easy. Yous just need to ready the SystemProperty Log4jContextSelector
to org.apache.logging.log4j.cadre.async.AsyncLoggerContextSelector
.
Y'all tin can do that by calculation the Organisation Property at runtime like so -
mvn jump-boot:run -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
or, when using a packaged jar -
mvn make clean package java -jar target/log4j2-demo-0.0.1-SNAPSHOT.jar -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
2. Using a mix of Sync and Async Loggers
You tin also utilise a mix of sync and async loggers with Log4j two using the <AsyncLogger>
configuration chemical element.
In the post-obit example, all the application specific logs will be asynchronous, and other root logs will be synchronous -
<Loggers > <AsyncLogger name = "com.case.log4j2demo" level = "debug" additivity = "simulated" > <AppenderRef ref = "ConsoleAppender" /> <AppenderRef ref = "FileAppender" /> </AsyncLogger > <Root level = "info" > <AppenderRef ref = "ConsoleAppender" /> <AppenderRef ref = "FileAppender" /> </Root > </Loggers >
Y'all don't need to add any SystemProperty when y'all're using <AsyncLogger>
element. Just add the above loggers to your log4j2.xml
file and you're prepare to become.
Conclusion
Congratulations folks! In this article, we learned how to integrate and configure Log4j two in Jump Boot apps. We also configured different types of appenders similar ConsoleAppender, RollingFile Appender, and SMTP Appender. Finally, nosotros learned how to utilise Async loggers provided by Log4j 2.
You can find the code for the sample project that nosotros congenital in this commodity in my github repository.
More than resources
You might also wanna check out the post-obit articles on Spring Boot configuration -
-
Configuring Bound Boot'south Server, GZip compression, HTTP/2, caching and much more than
-
Configuring Spring Kick to use Gson instead of Jackson
Thank you for reading. See you in the adjacent Post. Happy coding! :)
Source: https://www.callicoder.com/spring-boot-log4j-2-example/
0 Response to "Could Not Read Configuration File From Url [file://log4j.properties"
Post a Comment