简体   繁体   中英

How to append hostname to log file in log4j.xml

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

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 .

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 after tomcat-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>

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 .

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");

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());

I found that just ${hostName} by default would work for latest log4j

Something like this:

    <File name="file" fileName="${baseDir}/${hostName}-file.log" append="true">

This is documented under here: https://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration

In the Default Properites Section:

The default map is pre-populated with a value for "hostName" that is the current system's host name or IP address

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

try this : "${env:HOST}-${date:yyyy-MM-dd}" Hostname + Date . In yaml :

Properties:
    Property:
      - name: log-path
        value:  "logs"
      - name: filePattern
        value:  "${env:HOST}-${date:yyyy-MM-dd}"

  Appenders:

    Console:
      name: Console_Appender
      target: SYSTEM_OUT
      PatternLayout:
        pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

    File:
      name: File_Appender
      fileName: "${log-path}/filelog-${filePattern}.log"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM