tags:

views:

1078

answers:

3

Hi I am using log4j api to log the informations. I have used log4j_conffig.xml file for creating the log files. I have given the absolute path for each log file in param tag value.

eg :

appender name="GPREPROCESSOR_DEBUG" class="org.apache.log4j.DailyRollingFileAppender">
param name="DatePattern" value="'_'yyyyMMdd"/>
param name="File" value="D:/logFiles/GPreprocessor_Debug.log"/>
layout class="com.dnb.genericpreprocessor.common.log.AppXMLLayout"/>
/appender>

i do not want to give "D:/logFiles/" directly.Actually that path is dynamic based on my project location. so how can i give that

A: 

You have use ${java.home} or ${user.home} to define a relative path for your file. See log4help for more complete examples.

emeraldjava
A: 

You can create your own appender by extending from RollingFileAppender and adding a "prefix" attribute that can be defined according to your project. The filename that log4j uses is http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/FileAppender.html#setFile(java.lang.String), so it should be easy in ur appender class to use this and set the name of the file.

The other option is to use some property thats defined and available to log4j.xml (any java system property would do) and reference the filename as ${my.project.location}/logs/Preprocessor_Debug.log

rajasaur
+1  A: 

Any Java System property may be used in a log4j config file. For example, your application at its startup could do something like:

String directory = "logfiles"; // relative to "."
try {
  path = new File(directory).getCanonicalPath();
} catch (IOException e) {
  // Cannot use log4j yet, so complain to system out
  System.out.println("Could not get canonical path for " + directory, e);
}

System.setProperty("log.home", path);

// Now that we've configured log.home, start logging
DOMConfigurator.configureAndWatch("log4j_config.xml");

and then in your log4j configuration file use this properly like:

<param name="File" value="${log.home}/GPreprocessor_Debug.log"/>

The only downside of this is that you must define the system property before you initialize log4j logging. Of course, you can also define these parameters on the Java command line via "-Dlog.home=D:/logFiles" if that is more convenient.

Eddie