Peter Andersson
Peter Andersson

Reputation: 2047

Capture log4j output

We are using log4j2 extensively in our system, and configures it with log4j2.xml.

Now I need a new app that run jobs, and I want to separately capture all the logs resulted between time X and Y and put it in a database. Normal logging from our framework should occur as usual (to files or wherever log4j2.xml points to), But from time X to time Y.

I also want all the logging should be captured, preferably to a list of strings or something that can be saved in a database table.

My idea is to create a new Appender (that captures all logging output) and dynamically add/remove that appender to start and stop logging? Would that work? Can I reconfigure the loggers in the framework classes too?

Upvotes: 2

Views: 6856

Answers (2)

Paul Vargas
Paul Vargas

Reputation: 42060

It is possible. You need to create a custom appender. e.g.:

public class CustomAppender extends AbstractAppender {

    private List<String> list = new ArrayList<>();

    public CustomAppender(String name, Filter filter, Layout<? extends Serializable> layout) {
        super(name, filter, layout);
    }

    public CustomAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions) {
        super(name, filter, layout, ignoreExceptions);
    }

    @Override
    public void append(LogEvent event) {
        byte[] data = getLayout().toByteArray(event);
        list.add(new String(data).trim()); // optional trim
    }

    @Override
    public void stop() {
        // Write to the database
        System.out.println(list);
    }

}

Each event is converted to a string, which is added to the list. The stop method is automatically executed after removing the appender.

The following code exemplifies the use of this appender.

public static void main(String[] args) {
    // Execute some jobs
    for (int n = 0; n < 10; n++) {
        dummyJob(n);
    }
}

private static void dummyJob(int n) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();

    // Create and add the appender
    CustomAppender appender = new CustomAppender("Custom", null, PatternLayout.createDefaultLayout());
    appender.start();
    config.addAppender(appender);

    // Create and add the logger
    AppenderRef[] refs = new AppenderRef[]{AppenderRef.createAppenderRef("Custom", null, null)};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "com.company", "true", refs, null, config, null);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("com.company", loggerConfig);
    ctx.updateLoggers();

    // Run the job
    Logger logger = LogManager.getLogger("com.company");
    logger.info("Job {}", n);
    logger.info("Hello, World!");
    logger.info("This is awesome!");
    logger.info("Hope it works!");
    logger.info("Hope it helps!");

    // Remove the logger and appender
    config.removeLogger("com.company");
    config.removeAppender("Custom");
    ctx.updateLoggers();

}

The output of the latter:

[Job 0, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 1, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 2, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 3, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 4, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 5, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 6, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 7, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 8, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]
[Job 9, Hello, World!, This is awesome!, Hope it works!, Hope it helps!]

Upvotes: 9

You can use the log4j2 JDBC appender to store

http://logging.apache.org/log4j/2.x/manual/appenders.html#JDBCAppender

And the time filter to select when to log

http://logging.apache.org/log4j/2.x/manual/filters.html#TimeFilter

Upvotes: 0

Related Questions