Created
March 12, 2017 09:25
-
-
Save estani/29c58bf1f9b71f120dde1b056136fa15 to your computer and use it in GitHub Desktop.
Basic Log4j PatternLayout with elapsed time extension using joda time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stackoverflow; | |
import org.apache.log4j.PatternLayout; | |
import org.apache.log4j.spi.LoggingEvent; | |
import org.joda.time.Period; | |
import org.joda.time.format.PeriodFormatter; | |
import org.joda.time.format.PeriodFormatterBuilder; | |
import java.lang.management.ManagementFactory; | |
/** | |
* Shows how to extend PatternLayout to write your ouwn log entries. | |
* in this case it presfixes all lines with a human readable elapsed time prefix. | |
* looks like this: | |
* 0:00:15.904 - DEBUG [main] a test | |
*/ | |
public class TimeElapsedPatternLayout extends PatternLayout { | |
PeriodFormatter formatter = new PeriodFormatterBuilder() | |
.printZeroIfSupported() | |
.appendHours() | |
.appendSeparator(":") | |
.minimumPrintedDigits(2) | |
.appendMinutes() | |
.appendSeparator(":") | |
.appendSecondsWithMillis() | |
.appendLiteral(" - ") | |
.toFormatter(); | |
@Override | |
public String format(LoggingEvent event) { | |
//using upTime to be independent of the time this class get loaded | |
String prefix = formatter.print(new Period(ManagementFactory.getRuntimeMXBean().getUptime())); | |
return prefix + super.format(event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment