Reputation: 3919
Suppose I have a program with 20 classes, each with private static Logger logger = LoggerFactory.getLogger(SomeClass.class);
. These 20 classes will log warn, info, debug, or error.
Within one of the classes, how can I can access to all the errors logged in the program thus far (across all of the classes)? Note I'm not interested in dumping all these to a .log
, I want access to them from within the Java program.
Upvotes: 0
Views: 1703
Reputation: 10004
Use a custom appender to add to list which is singleton list using that you can access all the mismatch.
CustomAppender.java
public class CustomAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
@Override
protected void append(ILoggingEvent eventObject) {
if(eventObject.getLevel() == Level.WARN){
{
KPLogHolder.addData(eventObject.getMessage);
}
}
}
A singleton java class to hold messages KPLogHolder.java
public class KPLogHolder {
private static List<String> holder;
public static List<String> getLog(){
if(holder== null){
return new ArrayList<String>();
}
return holder;
}
public static void addData(String item){
getLog().add(item);
}
}
And accessing the mssage.
public class KPTest{
@Test
public void testLog(){
LOG.warn("Warning!!!!");
for(String str: KPLogHolder.getLog()){
System.out.println(str);
}
}
}
Note I've not used synchronization you need to implement those as ArrayList is not synced. Not sure why this requirement but be careful. most cases these goes to wrong implementation, there situation were it will bring down your server. if its not implemented properly.
Upvotes: 5
Reputation: 21
Not very difficult -
Either
Read log file
or
Overrider your log4j framework
so instead of logging to file, it should log data to java objects (this is going to be very memory intensive).
Upvotes: -1
Reputation: 531
Do you want to access it when all classes have logged the statement in the .log file or you want to keep accessing as and when the logging is happening.
If you want to access all the logs from those 20 classes after the logging funcation then why not read the .log file later in your other java program to access all the logs.
But i guess you need an indicator in your log file to determine those statementa have been logged by those 20 classes. say for example some string in the consoleappender configuration
Upvotes: 0