How to append hostname to log file in log4j.xml

核能气质少年 提交于 2019-11-29 09:48:48

问题


I want to append hostname and date to log file name.So log file Name should be like app_hostname.date.log. Note: This should run in both linux and windows.

<appender name="applog" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${path}/app.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>

And how to add filter based on the log pattern, not as StringMatchFilter.I want pattern to be matched. Thanks in advance


回答1:


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>



回答2:


Following the log4j2 documentation you can do environment variable lookups, so in Unix-like systems this should work:

<Property name="MYHOST">${env:HOSTNAME}</Property>
<Appenders>
  <File name="File1" fileName="${MYHOST}_file.log">
  ...
  </File>
</Appenders>

Beware that $HOSTNAME is not always available by default and you might need to export it explicitly in the shell, see this post.




回答3:


Following configuration will do the trick

<appender name="file" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false" />
        <param name="maxFileSize" value="10MB" />
        <param name="maxBackupIndex" value="10" />
        <param name="file" value="C:\\Users\\kavurira\\Desktop\\log4j-${HostName}.log" />
        <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" 
            value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m${HostName}%n" />
        </layout>
    </appender>

Just set "HostName" as system property, before initialization of Log4j.

System.setProperty("HostName", InetAddress.getLocalHost().getHostName());



回答4:


You can defined a system property hostname and change the configuration:

<param name="File" value="${path}/app_${hostname}.log" />

Make sure the system property is set before log4j initialization.

For adding filter, please refer the answer of Filter log by matching pattern - log4j

UPDATED: A simple solution for writing different log:

<logger name="com"><!-- for Class Package is com.???... -->
    <level value="INFO" />
    <appender-ref ref="applog" />
</logger>
<logger name="loggerForCustomClass">
    <level value="INFO" />
    <appender-ref ref="customlog" />
</logger>

Change code in your program:

//message will write to "customlog" appender
Logger.getLogger("loggerForCustomClass").info("log from custom class");

//message will write to "applog" appender
Logger.getLogger(getClass()).info("log from other class");



回答5:


Cf. this response to a similar question, the request wouldn't be obvious to satisfy, even if according to this mailing-list thread, this is a long-standing request.

Using a recent version of log4j, the end of this documentation section seems you already have the feature available using properties.

Anyway, you always have the solution to do it yourself with a specialized pattern layout, like here.




回答6:


Write you own custom appender extending the basic appenderws. This will help you to manipulate the properties in java.

See This answer https://stackoverflow.com/a/1324075/1594992

Or Simply set the command line arguments & system property like this answer

https://stackoverflow.com/a/4953207/1594992



来源:https://stackoverflow.com/questions/36170962/how-to-append-hostname-to-log-file-in-log4j-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!