Dynamic Log Location for log4j

I was really surprised that log4j doesn’t have any facility to set the log file location with a relative path. Hard to build a portable application if you need to set the full value of a local path. And don’t talk to me about config files, because that requires reading documentation, which is only read less than it is written.

So, if you use the standard log4j servlet approach to start your logging, you can weave in the following to set your path relative to your app:

org.w3c.dom.NodeList nodes = doc.getElementsByTagName("param");;
org.w3c.dom.Node node = null;//nodes.item(0);
org.w3c.dom.NamedNodeMap nodeMap = null;
for(int i=0; i < nodes.getLength(); i++)
{
    node = nodes.item(i);
    nodeMap = node.getAttributes();
    if(nodeMap.getNamedItem("name")
        .getNodeValue().equals("File"))
    {
        node = nodeMap.getNamedItem("value");
        outputFile = new File(getServletContext().getRealPath(node.getNodeValue()));
        outPutPath = outputFile.getAbsolutePath();
        outPutPath = outPutPath.replace('', '/');
        node.setNodeValue(outPutPath);
    }
}

Then you can set the log location to outPutPath.

Enjoy 🙂

Facebooktwitterredditlinkedinmail
© Scott S. Nelson

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.