2 Minutes To Code (β Version)

Log4j - 2 minute tutorial

How to make log files rotate based on size programmatically

		package com.techfundaes.log4j;

		import org.apache.log4j.Layout;
		import org.apache.log4j.Logger;
		import org.apache.log4j.PatternLayout;
		import org.apache.log4j.rolling.RollingFileAppender;
		import org.apache.log4j.rolling.TimeBasedRollingPolicy;

		public class ProgrammaticConfigArchiveRollingFileOnTimePeriod
		{
			public static void main(String[] args)
			{
				Logger logger = Logger.getLogger(ProgrammaticConfigArchiveRollingFileOnTimePeriod.class);
				Layout layout = new PatternLayout("%d [%t] %-5p (%F:%L) - %m%n");
				RollingFileAppender rollingFileAppender = new RollingFileAppender();
				rollingFileAppender.setLayout(layout);
				rollingFileAppender.setFile("worker.log");
				TimeBasedRollingPolicy timeBasedRollingPolicy = new TimeBasedRollingPolicy();
				timeBasedRollingPolicy.setFileNamePattern("worker-.%d{yyyyMMdd-HHmm}.log.gz");
				rollingFileAppender.setRollingPolicy(timeBasedRollingPolicy);
				rollingFileAppender.activateOptions();
				logger.addAppender(rollingFileAppender);
				
				while(true)
					logger.info("Logged this message!!!");
			}
		}