Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify log directory of log4j2 in java code?

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?

like image 618
rainbow Avatar asked Sep 20 '25 02:09

rainbow


1 Answers

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;
}
like image 58
rainbow Avatar answered Sep 21 '25 17:09

rainbow