首先从您的Java代码执行此操作, 然后 将log4j配置 到应用程序中,
注意:在执行以下代码时,处理或捕获所需的异常。
// step-1 : set hostName into System's property, which will use by log4jSystem.setProperty("hostName", InetAddress.getLocalHost().getHostName()); //step - 2 : set currentDate into System's property, which will use by log4jSystem.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");更新 :
如果您的应用程序是Web应用程序,则需要在
tomcat-server启动后和
application运行之前配置我们想要的属性,
为此,创建一个实现了接口的类
ApplicationConfiguration
,该类
ServletContextListener有助于在任何应用程序运行之前先运行。
照样做
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(); } }}......
同样设置您的log4j.xml文件,
<appender name="applog" > <param name="File" value="${path}/app_${hostName}.${currentDate}.log" /> <param name="MaxFileSize" value="1MB" /> <param name="DatePattern" value=".dd-MM-yyyy" /> <layout > <param name="ConversionPattern" value="[%d{dd-MM-yyyy HH:mm:ss}] [%-5p] %m%n"/> </layout></appender>请相应地更新web.xml文件,
<web-app ...> <listener> <listener-class> com.pck1.ApplicationConfiguration </listener-class> </listener></web-app>
web.xml之所以需要应用此配置,是因为应用程序启动时会像Context-listener一样遵循它。
更新2:
<logger name="packageName.AAA" additivity="false" > <level value="INFO" /> <appender-ref ref="applog"/> </logger>



