How to give dynamic file name in the appender in log4j.xml

后端 未结 5 1678
情深已故
情深已故 2020-11-28 06:16

I am using log4j to log information. I have used a log4j.xml file for creating log files. I have given the absolute path for each log file as a param

相关标签:
5条回答
  • 2020-11-28 06:21

    Below is my code for using Log4J for dynamically generate filename. It changes its name according to input file name and current date-time. (So helpful in case you run same file multiple times.)

    public class LogClass {
    
        private static Logger log =  Logger.getLogger(LogClass.class);
        private static boolean initializationFlag = false;
        private static String fileName;
    
        private static void intializeLogger(){
            log.setLevel(Level.DEBUG);
    
            DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            Date date = new Date();
    
            RollingFileAppender appender = new RollingFileAppender();
            appender.setAppend(true);
            appender.setMaxFileSize("1MB");
            appender.setMaxBackupIndex(1);
            appender.setFile(fileName + "_" + dateFormat.format(date) + ".log");
            appender.activateOptions();
    
            PatternLayout layOut = new PatternLayout();
            layOut.setConversionPattern("%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");
            appender.setLayout(layOut);
    
            log.addAppender(appender);
        }
    
        public static Logger getLogger(){
            if(initializationFlag == false){
                intializeLogger();
                initializationFlag = true;
                return LogClass.log;
            }
            else{
                return LogClass.log;
            }
        }
    
        public static void setFileName(String fileName){
            LogClass.fileName = fileName;
        }
    }
    

    Now whenever you want to use logger in your program, Just write these two lines :

    LogClass.setFileName(yourFileName);
    LogClass.getLogger().debug("hello!!");
    

    Happy Coding.

    0 讨论(0)
  • 2020-11-28 06:28

    It's much easier to do the following:

    In log4j.xml define variable as ${variable}:

    <appender name="FILE" class="org.apache.log4j.FileAppender">    
        <param name="File" value="${logfilename}.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d::[%t]::%-5p::%c::%x - %m%n" />
        </layout>       
    </appender>
    

    Then make sure you set the system property when you start your JVM such as:

    java -Dlogfilename=my_fancy_filename  example.Application
    

    That will create a dynamic log file name: my_fancy_filename.log

    Alternatively, you can set the system property in code so long as you do it before you create a logger (this is useful if you want your PID in your logs for instance). Such as:

    System.setProperty("logfilename", "a_cool_logname");
    

    Once that is set you can go ahead and get your loggers as normal and they will log to the dynamic file (be careful of those static Loggers that create loggers before your main method executes).

    0 讨论(0)
  • 2020-11-28 06:31

    Before executing anything, log4j thoroughly checks the class path for log4j.xml configuration file. Let'say, by chance, if there is any log4j.xml configuration file in the library jars you referenced in your project, log4j loads that file as the configuration file and starts logging. In this context, when you are setting log file location in your FileAppender dynamically by getting the value from System properties as suggested by @Big B, it will not work since log4j had already loaded the configuration file it discovered first.

    To prevent this, you can use DOMConfigurator to inform log4j what configuration file it should load and when it should load. So, as soon as you set the system property of LogFileLocation in your program use DOMConfigurator to load intended properties file in the following way:

    System.setProperty("LogFileLocation", "D:Test/Logdetails"));
    DOMConfigurator.configure("log4j.xml");
    

    By doing this way, you will load log4j.xml after you set the system property LogFileLocation in your program. (It will also override the already loaded configuration)

    Inside the log4j.xml configuration, you set the file location in the param tag 'File':

    <appender name="fileAppender"
            class="org.apache.log4j.FileAppender">
            <param name="File" value="${LogFileLocation}.log" />
            <param name="Append" value="false" /> 
    <!-- false will make the log to override the file. true will make the log to append to the file -->
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern"
                    value="%d{dd/MM/yyyy HH:mm:ss} %-5p %c{2} 
            - %m%n" />
            </layout>
        </appender>
    

    To understand whatever I said better, provide -Dlog4j.debug=true in your VM arguments and see the log of log4j execution in your console.

    0 讨论(0)
  • 2020-11-28 06:36

    It makes more sense to extend FileAppender with your own class, in which you override setOptions() method. Then in your log4j.properties you configure root to log to yourpackage.yourFileAppender, which is much cleaner.

    0 讨论(0)
  • 2020-11-28 06:38

    In your class containing main method set the name of your class to some system property. In following example I used log_dir as property name.

    class ABC{
     public static void main(String s[]){
      System.setProperty("log_dir", ABC.class.getSimpleName());
     }
    }
    

    And in your log4j.xml file use log_dir property in File param's value attribute

    <appender name="FA" class="org.apache.log4j.DailyRollingFileAppender">
      <param name="DatePattern" value="'_'yyyyMMdd"/>
      <param name="File" value="D:/logFiles/${log_dir}"/>
      <layout class="com.dnb.genericpreprocessor.common.log.AppXMLLayout"/>
    </appender>
    

    Works like a charm

    0 讨论(0)
提交回复
热议问题