I configured spring with transactional support. Is there any way to log transactions just to ensure I set up everything correctly? Showing in the log is a good way to see wh
Here is some code I use in my Logback Layout implementation derived from ch.qos.logback.core.LayoutBase.
I create a thread-local variable to store the reference to the method org.springframework.transaction.support.TransactionSynchronizationManager.isActualTransactionActive(). Whenever a new log line is printed out, getSpringTransactionInfo() is called and it returns a one-character string that will go into the log.
References:
Code:
private static ThreadLocal txCheckMethod;
private static String getSpringTransactionInfo() {
if (txCheckMethod == null) {
txCheckMethod = new ThreadLocal() {
@Override public Method initialValue() {
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Class> tsmClass = contextClassLoader.loadClass("org.springframework.transaction.support.TransactionSynchronizationManager");
return tsmClass.getMethod("isActualTransactionActive", (Class>[])null);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
}
assert txCheckMethod != null;
Method m = txCheckMethod.get();
String res;
if (m == null) {
res = " "; // there is no Spring here
}
else {
Boolean isActive = null;
try {
isActive = (Boolean) m.invoke((Object)null);
if (isActive) {
res = "T"; // transaction active
}
else {
res = "~"; // transaction inactive
}
}
catch (Exception exe) {
// suppress
res = "?";
}
}
return res;
}