N N
N N

Reputation: 1638

How to assign log4j output message to a variable

I want to assign log4j message that goes to console to my variable, for instance:

log.info("some info");
String info = // info message from log

how can I accomplish this?

Upvotes: 1

Views: 795

Answers (2)

Andrew
Andrew

Reputation: 49646

Message message = new SimpleMessage("some info");

PatternLayout layout = PatternLayout.createDefaultLayout();
Log4jLogEvent event = Log4jLogEvent.newBuilder()
                                   .setLevel(Level.INFO)
                                   .setMessage(message)
                                   .build();

String formattedMessage = layout.toSerializable(event);

The process of forming an exact string that the logger is up to print is quite tedious. You need to programmatically describe the settings you normally write in a configuration file. Then, you should build an event that will give the context to your settings.

For the sake of simplicity, I took the default layout, and built an event with a simple INFO message. But I am pretty sure there should be a way to load the configuration from an external source. Try: PatternLayout.createPatternParser(Configuration).

Upvotes: 1

Vsevolod Kaimashnikov
Vsevolod Kaimashnikov

Reputation: 23

I don't understand for what, I think you message is more complex that simple string. You can try to implement own custom java Appender and to register it in Logger. Appender will work as listener of messages and you will be able to implement some custom logic.

Upvotes: 1

Related Questions