I have tried to write a custom appender using log4j2.its working fine its print a logs in console. But I want to write a custom webservice appender using log4j2.
this is my custom appender class.
@Plugin(name = "MyCustomAppender", category = "Core", elementType = "appender", printObject = true)
public class MyCustomAppender extends AbstractAppender {
protected MyCustomAppender(String name, Filter filter,
Layout layout, String filename) {
super(name, filter, layout);
// TODO Auto-generated constructor stub
}
@PluginFactory
public static MyCustomAppender createAppender(@PluginAttribute("name") String name,
@PluginAttribute("fileName") final String fileName,
@PluginElement("Layout") Layout layout,
@PluginElement("Filters") Filter filter) {
return new MyCustomAppender(name, filter, layout,fileName);
}
@Override
public void append(LogEvent arg0) {
// TODO Auto-generated method stub
System.out.println("inside appender: " +arg0);
}
}
my log4j2.xml is
I have different logs in my application i.e transaction logs, audit logs, and exception logs.these can be post into a service. i am calling this service using
logapplication as shown in bellow architecture.please provide any sample code or any suggestions on this.
Solved
As far as I can see you are on the right track. You have successfully created a custom appender, configured it and confirmed that it is working (logging to the console).
The next step would be to:
- In the
append(LogEvent)method, do something to send this information to your external service. TheLogEventobject implementsjava.io.Serializable, so serializing the log events may be the simplest way to turn this information into bytes. The details depend on the API of the external service you select. - In your configuration, you may want to distinguish between the various types of log events (you mention audit, transactions and exceptions). I recommend you take a look at Log4j2 Markers. This provides a clean way to tag specific log events so they can be handled differently downstream. The alternative is to configure separate loggers for these types, but this will get messy very quickly.
Comments
Post a Comment