milosdju
milosdju

Reputation: 803

Can I collect logs (messages) from log4j into one java object

Instead of printing it to the console or writing in some file I want to collect all logs (i.e. messages) into some collection of String in Java object like this:

class LogCollector {
    List<String> messages;
}

That would make it easier for me to generate custom HTML report (just passing "LogCollector" object into some of methods). It would be preferable if I can implement this with Log4J.

MORE DETAILED ISSUE: I want to make some class "LoggingPart":

class LoggingPart {
    String name;
    List<String> messages;
    List<LoggingPart> parts = new ArrayList<>();

    public static void start(String name) {
        parts.add(new LoggingPart(name));

        /* Logic that after every call LoggingPart.start("someName")  */
        /* in some other class will start collecting messages from    */
        /* logger into LoggingPart instance of name "someName"        */

        /* Report will be generated only of messages from particular  */
        /* instance with specified name                               */
    }
}

Upvotes: 0

Views: 1136

Answers (1)

milosdju
milosdju

Reputation: 803

I have been recommended many things, among all creating custom TestNG listener but the solution is really simple: make an additional log4j Appender:

  1. Add Appender in log4j config file (log4j.properties)
  2. Make a reference to your custom Appender class which will contain method for handling logs

Upvotes: 0

Related Questions