February 8, 2010

Using Log4j and Streaming the Logs as per instance/file

The following setup can be used to generate a simple logging mechanism which will log the information on a per instance per file basis.

A simple log4j.properties file setup.

 
#### Use two appenders, one instance logs to X another to Y
log4j.logger.X=debug, X
log4j.logger.Y=debug, Y

log4j.appender.X.layout=org.apache.log4j.SimpleLayout
log4j.appender.X=org.apache.log4j.FileAppender
log4j.appender.X.File=exampleX.log

log4j.appender.Y.layout=org.apache.log4j.SimpleLayout
log4j.appender.Y=org.apache.log4j.FileAppender
log4j.appender.Y.File=exampleY.log

A Java code that decides which logger to use.

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class FormatNumber
{    public static void main (String args[])
    {
        BigDecimal b = new BigDecimal("-1232323222.1049");
        BigDecimal c = b.setScale(4,BigDecimal.ROUND_HALF_DOWN);

        DecimalFormat format = new DecimalFormat("#,##0.00");
        String o = format.format(c);

        BigDecimalRounder g = new BigDecimalRounder("-1232323222.1049","Y");
        c = g.roundUpToScale(2, BigDecimal.ROUND_HALF_UP);
    }
}

import java.math.BigDecimal;
import java.util.Enumeration;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;

public class BigDecimalRounder extends BigDecimal
{
    private Logger log = null;
    public BigDecimalRounder(String decimal, String name)
    {
        super(decimal);
        log = Logger.getLogger(name);
    }

    public BigDecimal roundUpToScale(int scale, int roundingMode)
    {
        BigDecimal returnDecimal = null;
        if (super.scale() >= scale)
        {
            int j = super.scale();
            while (j >= scale)
            {
                returnDecimal = super.setScale(j, roundingMode);
                log.debug("log to file: " + returnDecimal.toString());
                j--;
            }
        }
        return returnDecimal;
    }
}