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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36170962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:30:58  来源:igfitidea点击:

How to append hostname to log file in log4j.xml

javalogginglog4jlogfile

提问by Prasanna Kumar H A

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.

我想将主机名和日期附加到日志文件名。所以日志文件名应该像app_hostname.date.log注意:这应该在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. Thanks in advance

以及如何根据日志模式添加过滤器,而不是像StringMatchFilter.I 想要匹配的模式。提前致谢

采纳答案by Vishal Gajera

Do this first from your java codethenconfigure log4jinto 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 aftertomcat-serverstart and before any applicationrun,

如果您的应用程序是网络应用程序,则需要在tomcat-server启动后和任何application运行之前配置我们想要的属性,

for that create one class ApplicationConfigurationwhich has ServletContextListenerinterface implemented which helps here to run first before any application runs.

为此,创建一个实现了接口的类ApplicationConfigurationServletContextListener这有助于在任何应用程序运行之前首先运行。

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.xmlbecause 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>

回答by Dfaure

Cf. this responseto 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 sectionseems 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.

无论如何,您总是可以通过专门的模式布局自行解决,例如这里

回答by Beck Yang

You can defined a system property hostnameand 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");

回答by Rajesh Kumar

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

回答by Sam

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

编写您自己的自定义 appender,扩展基本 appenderws。这将帮助您操作 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

回答by Jose Duarte

Following the log4j2 documentationyou 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 中显式导出它,请参阅此帖子

回答by Alferd Nobel

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

试试这个:"${env:HOST}-${date:yyyy-MM-dd}"主机名+日期。在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"