My application has logging system created by me. However i would like to replace it by log4j2. But i've met a problem with configuration of logging directory in log4j2. Yes, i know there is possibility to log into fixed directory described in config file:
<RandomAccessFile name="FILE" fileName="l4j2/${date:yyyy-MM-dd_hh-mm-ss}.log" append="true" immediateFlush="false">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-6p %C{1}.%t:%L >>> %m%n"/>
</RandomAccessFile >
But i want to log data in users "My document" directory which can be specific during launching of java app. Is it even possible?
You can use a system property in the file name. See the system properties section of the Lookup manual page.
Example:
<RandomAccessFile name="FILE"
fileName="${sys:logFolder}/l4j2/${date:yyyy-MM-dd_hh-mm-ss}.log"
append="true" immediateFlush="false"> ...
You can even specify a default in case the system property is not defined. The syntax is ${sys:KEY:-DEFAULT}
. For example:
${sys:logFolder:-/var/tmp}
I've figured it out.
Modify log4j2.xml from
<RandomAccessFile name="FILE" fileName="l4j2/${date:yyyy-MM-dd_hh-mm-ss}.log" append="true" immediateFlush="false">
to:
<RandomAccessFile name="FILE" fileName="${sys:log4j.saveDirectory}/${date:yyyy-MM-dd_hh-mm-ss}.logd" append="true" immediateFlush="false">
Add to java code:
System.setProperty("log4j.saveDirectory", getMyDocuments());
You can estimate user's "My document" with this method:
String getMyDocuments()
{
String out = ".\\";
try
{
Process process = Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal");
process.waitFor();
StringWriter sw = new StringWriter();
int c;
while ((c = process.getInputStream().read()) != -1)
{
sw.write(c);
}
String output = sw.toString().replaceAll("\t", " ");
String[] parsed = output.split("\\t|\\s{2,}");
}
catch (Exception e)
{
e.printStackTrace();
}
return out;
}
In the case of log4j2, you can use,
# May change log file path as per the need
property.filename = ${sys:user.dir}/logs/debug.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.