简体   繁体   English

如何将主机名附加到 log4j.xml 中的日志文件

[英]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 .我想将主机名和日期附加到日志文件名。所以日志文件名应该像app_hostname.date.log Note: This should run in both linux and windows.注意:这应该在linux 和 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.以及如何根据日志模式添加过滤器,而不是StringMatchFilter 。我希望模式匹配。 Thanks in advance提前致谢

Following the log4j2 documentation you can do environment variable lookups, so in Unix-like systems this should work:按照 log4j2文档,您可以进行环境变量查找,因此在类 Unix 系统中,这应该可以工作:

<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 .请注意,默认情况下 $HOSTNAME 并不总是可用,您可能需要在 shell 中显式导出它,请参阅此帖子

Do this first from your java code then configure log4j into application,首先从您的 Java 代码执行此操作,然后将 log4j 配置到应用程序中,

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,如果您的应用程序是 web 应用程序,那么需要在tomcat-server启动之后和任何application运行之前配置我们想要的属性,

for that create one class ApplicationConfiguration which has ServletContextListener interface implemented which helps here to run first before any application runs.为此,创建一个ApplicationConfiguration类,它实现了ServletContextListener接口,这有助于在任何应用程序运行之前首先运行。

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,同样设置你的 log4j.xml 文件,

<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.xml 文件,

<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.这个配置需要应用到web.xml因为应用程序在启动时,通过这个配置它会像 Context-listener 一样跟随它。


UPDATE 2 :更新 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.使用最新版本的 log4j,本文档部分的结尾似乎您已经拥有使用属性可用的功能。

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:您可以定义系统属性hostname并更改配置:

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

Make sure the system property is set before log4j initialization.确保在 log4j 初始化之前设置系统属性。

For adding filter, please refer the answer of Filter log by matching pattern - log4j添加过滤器请参考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我发现${hostName}默认情况下适用于最新的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这在此处记录: 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默认映射预先填充了“hostName”的值,即当前系统的主机名或 IP 地址

Write you own custom appender extending the basic appenderws.编写您自己的自定义 appender,扩展基本 appenderws。 This will help you to manipulate the properties in java.这将帮助您操作 java 中的属性。

See This answer https://stackoverflow.com/a/1324075/1594992请参阅此答案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/a/4953207/1594992

try this : "${env:HOST}-${date:yyyy-MM-dd}" Hostname + Date .试试这个: "${env:HOST}-${date:yyyy-MM-dd}" Hostname + Date 。 In yaml :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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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