Posts tagged ‘logging’

Log4Net configuration and scope extension

I had the need to setup Log4Net logging in a new project the other day. It is fairly easy to setup, just add the listeners you want in the configuration files. Then use it, of course you get most things for free the log level etc. We also wanted to make it super easy to use Scope, so I added a LogExtension that takes care of that. The idea is if you forget to close the scope it will be automatically done once the scope object gets garbage collected. Below is example code including UnitTests.

logger_sample

Java log4J

I had the need to log from a java project I just created. Never used log4J before but heard good things. Man do I love it when things are simple and that’s just what log4J is. Download and extract the jar, in my case log4j-1.2.16.jar add it to your classpath and your off to the races. When reading the install document, they have what you need to get up and running ASAP a small HelloWorld that will get you going.

import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
   
public class Hello
{
      private static final Logger logger = Logger.getLogger(Hello.class);
      public static void main(String argv[])
      {
        BasicConfigurator.configure();
        logger.debug(“Hello world.”);
        logger.info(“What a beatiful day.”);
      }
}

Create the file from the sample and compile
> javac Hello.java
and run it
> java Hello

It will give the following output
0 [main] DEBUG Hello – Hello world.
6 [main] INFO Hello – What a beatiful day.

Yes, super simple, of course it has all the bells and whistles you might need. Like logging just for a specific class or just at a certain level, log to file etc, etc,

UPDATE
Then you can create xml file and configure the appenders from there, below is a sample of console appender and then a file appender. To set it in code, you can use the following.

PropertyConfigurator.configureAndWatch( “log4j_config.xml” );

That will instruct log4J to monitor your configuration file. If you want to change the configuration on the fly all you need to do is to change your configuration file, log4J checks for changes every 60 seconds. You can also call with additional parameter setting your own frequency.

# Set root logger level and appenders
log4j.rootLogger=INFO, console, rollingFile

# Console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss,SS} %-4r [%t] %-5p %c %x – %m%n

# Rolling file appender
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=mylog.log
log4j.appender.rollingFile.MaxFileSize=5MB
log4j.appender.rollingFile.MaxBackupIndex=20
log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss,SS} %-4r [%t] %-5p %c %x – %m%n