One of the common requirement in Java projects, that are using Log4j, and want to write logs into different files for each module (or layer) in the project. For example, if you have a an application and you may want to log the messages from the service layer to a service.log file and the log messages from the DAO layer to the DAO.log file and so on. This is very simple to achieve using Log4j. EVEN you can differentiate logs for EACH Java class with the project.
Now call the below method loadLog4jConfig(this) from the class for which you want to differentiate log file. A common practice is to call the below method from the constructor of the class. It will runtime generate a log file named as that of class name and will write all corresponding logs into this particular log file.
Note: There are so many others ways also, however the above method is the simplest way to write logs into different files.
log.properties
# Root logger option
log4j.rootLogger=INFO, stdout, file
# Redirect log messages to console
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-MM-dd HH:mm:ss}] %-5p %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logs/default_Logs.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}] %-5p %m%n
Now call the below method loadLog4jConfig(this) from the class for which you want to differentiate log file. A common practice is to call the below method from the constructor of the class. It will runtime generate a log file named as that of class name and will write all corresponding logs into this particular log file.
public static void loadLog4jConfig(Object obj) { try { Class<?> thisClass = (obj.getClass()); String CLASS_NAME = thisClass.getSimpleName(); String logFileName = "logs/" + CLASS_NAME + ".log"; Properties props = new Properties(); InputStream configStream = thisClass.getResourceAsStream("/log4j.properties"); props.load(configStream); configStream.close(); props.setProperty("log4j.appender.file.File", logFileName); LogManager.resetConfiguration(); PropertyConfigurator.configure(props); } catch (Exception e) { e.printstacktrac(); } }
Note: There are so many others ways also, however the above method is the simplest way to write logs into different files.