I’m writing a database log4j appender in Play.
On its append() method, it creates a new instance of a model entity Log4jLine, and saves() it via JPA.
This works fine on debug/info logs. However, exceptions are not logged.
There is a call to this appender from framework code, but I suspect it is not working because the JPA session is not valid at this point.
How would I adapt the code to support this use case?
public class DBAppender extends AppenderSkeleton {
@Override
protected void append(LoggingEvent loggingEvent) {
Log4jLine logLine = new Log4jLine(...);
logLine.save();
}
}
Per our conversation above I was curious about how to do this and was able to get this to work. Essentially, you need to create a new EntityManager and fully manage it yourself. Calling any of the Play built-ins (.save(), .merge(), etc) will cause them to use the EntityManager that Play sets up for you. However, if you revert to standard JPA calls, it will work.
This is just a quick and dirty experiment to prove the point. You’ll obviously need to handle exceptions and failure cases in logException() that I’m not handling. And just for clarity, Notification is a basic object in my project I was able to use for this quickly.
Hope that helps!