Last active
August 29, 2015 14:01
-
-
Save flurrydev/f0a503177e949f9ae9e1 to your computer and use it in GitHub Desktop.
LogRequestAppender Sample Code
This file contains hidden or 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
import org.apache.log4j.AppenderSkeleton; | |
import org.apache.log4j.Layout; | |
import org.apache.log4j.spi.ErrorCode; | |
import org.apache.log4j.spi.LoggingEvent; | |
import java.io.Writer; | |
public class LogRequestAppender extends AppenderSkeleton | |
{ | |
@Override | |
protected void append(LoggingEvent event) | |
{ | |
String loggingKey = LogRequestFilter.getLoggingKey(); | |
if(loggingKey == null) { | |
// This thread has not been tagged for logging. Append nothing | |
return; | |
} | |
Writer writer = getWriter(loggingKey); | |
try { | |
writer.append(this.layout.format(event)); | |
// In log4j, the appender is responsible for formatting the Throwable if the layout doesn't handle it. | |
if(layout.ignoresThrowable()) { | |
String[] throwableStrRep = event.getThrowableStrRep(); | |
if (throwableStrRep != null) { | |
for(String s : throwableStrRep) { | |
writer.append(s); | |
writer.append(Layout.LINE_SEP); | |
} | |
} | |
} | |
} catch(Exception e) { | |
errorHandler.error("Failure to write to LogRequestAppender", e, ErrorCode.WRITE_FAILURE, event); | |
} | |
} | |
private Writer getWriter(String loggingKey) | |
{ | |
/* Get a writer using the loggingKey. Not implemented in this sample code. | |
This could write to a database, disk, or even keep logs in-memory. In-memory logs could be made accessible on | |
a privately accessible webserver endpoint. Ideally the writer should key on the loggingKey, so that these | |
are easily accessible by key. | |
The only important thing is that the output of the logs is somehow accessible to engineers, and has an | |
appropriate level of restriction */ | |
return null; | |
} | |
@Override | |
public boolean requiresLayout() | |
{ | |
return true; | |
} | |
// No resources to close | |
@Override public void close() { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment