Do this first from your java code then configure log4j into application,
NOTE : handle or catch required Exception while below code execute.
// step-1 : set hostName into System's property, which will use by log4j
System.setProperty("hostName", InetAddress.getLocalHost().getHostName());
//step - 2 : set currentDate into System's property, which will use by log4j
System.setProperty("currentDate", new SimpleDateFormat("dd-MMM-yyyy").format(new Date()));
//step - 3 : now configure/load log4j into Application , if it's not still loaded earlier then.
org.apache.log4j.Logger LOG = Logger.getLogger(YourJavaClassName.class); // ALERT : before this step above 2-step must needs to be execute, otherwise file-name won't appear as you required.
//LOG.debug("anything whatever programmer what to log");
UPDATED :
If your application is web-application,
then need to configure property which we want here aftertomcat-server
start and before any application
run,
for that create one class ApplicationConfiguration
which has ServletContextListener
interface implemented which helps here to run first before any application runs.
do likewise,
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ApplicationConfiguration implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
// step-1 : set hostName into System's property, which will use by log4j
System.setProperty("hostName", InetAddress.getLocalHost().getHostName());
//step - 2 : set currentDate into System's property, which will use by log4j
System.setProperty("currentDate", new SimpleDateFormat("dd-MMM-yyyy").format(new Date()));
} catch (UnknownHostException e) {
System.out.println("Error Message : " + e.getMessage());
//e.printStackTrace();
}
}
}
......
Set your log4j.xml file likewise,
<appender name="applog" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="${path}/app_${hostName}.${currentDate}.log" />
<param name="MaxFileSize" value="1MB" />
<param name="DatePattern" value=".dd-MM-yyyy" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd-MM-yyyy HH:mm:ss}] [%-5p] %m%n"/>
</layout>
</appender>
please, update web.xml file accordingly,
<web-app ...>
<listener>
<listener-class>
com.pck1.ApplicationConfiguration
</listener-class>
</listener>
</web-app>
This configuration need to apply into web.xml
because application
when start, by this configuration it will follow it like
Context-listener.
UPDATE 2 :
<logger name="packageName.AAA" additivity="false" >
<level value="INFO" />
<appender-ref ref="applog"/>
</logger>
logback
orlog4j2
. start wtih logback'sSiftingAppender
– Priapus