4

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?

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.