Log4j is a simple and flexible logging framework. Logging equips the developer with detailed context for application failures. With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost.
Two most common configuration options are in practice industry wide i.e. using xml configuration and using properties configuration.
In this post, I am showing the example code for configuring log4j using properties file.
Step 1) Create a maven java project and update log4j dependencies
Follow the steps given in this post related to configuring log4j with maven.
Step 2) Create log4j.properties file
This is the main properties file having all runtime configuration used by log4j. This file will have appenders information, log level information and output file names for file appenders.
Step 3) Configure log4j.properties and test the application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| package default; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class Log4jPropertiesConfigurationExample { static Logger logger = Logger.getLogger(Log4jPropertiesConfigurationExample. class ); public static void main(String[] args) { //PropertiesConfigurator is used to configure logger from properties file PropertyConfigurator.configure( "log4j.properties" ); //Log in console in and log file logger.debug( "Log4j appender configuration is successful !!" ); } } |
Output in console and demoApplication.log in project root folder:
No comments:
Post a Comment