Ok, in that case this is the right post for you.
Lets take an ordinary (synchronous) file logger from Log4j 1.x ( tested with 1.2.17) and wrap it up with a 'cool' AsyncAppender. :D.
Considering that you have
import org.slf4j.Logger ... static Logger log = LoggerFactory.getLogger("MyLogger");
You turn your internal sync appender into an async with:
static { AsyncAppenderBuilder.wrapAsyncAppender(log, "MyAppndrName") }
Then use just like a regular logger
The helping class looks like this:
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
import org.apache.log4j.Appender | |
import org.apache.log4j.AsyncAppender | |
import org.slf4j.impl.Log4jLoggerAdapter | |
/** | |
* Replaces the original sync appender with an async appender | |
* @author arrizabalaga | |
*/ | |
class AsyncAppenderBuilder { | |
private static int DEFAULT_BUFFER_SIZE=500 | |
/** | |
* Looks for an appender in the logger, wraps it with an async and deletes the original appender. | |
* @param loggerAdapter slf4j logger adapter | |
* @param nombreAppender name of the sync appender to be wrapped | |
*/ | |
static void wrapAsyncAppender(Log4jLoggerAdapter loggerAdapter,String appenderName,int bufferSize=DEFAULT_BUFFER_SIZE) { | |
//Take original appender | |
org.apache.log4j.Logger log4jLogger=loggerAdapter.logger | |
Appender syncAppender=log4jLogger.getAppender(appenderName) | |
//Wrap it | |
AsyncAppender asyncAppender=new AsyncAppender() | |
asyncAppender.setBufferSize(bufferSize) | |
asyncAppender.addAppender(syncAppender) | |
//Add the async | |
log4jLogger.addAppender(asyncAppender) | |
//Remove the sync | |
log4jLogger.removeAppender(syncAppender) | |
} | |
} |
Iván.