Using org.apache.log4j.jdbc.JDBCAppender
, how can I get stracktraces logged with warn
and error
into the PatternLayout
.
I'm logging like
logger.warn("warning description", e);
logger.error("error description", e);
I get the String descriptions into the table, but the Throwable's stacktrace is now where. Is there another parameter that I can access via the PatternLayout
. Currently I am using
"INSERT INTO app_logs (app, log_date, log_level, location, loc, message) VALUES ('my-apps-name', '%d{ISO8601}','%p', '%C.java', '%C{1}.java:%L', '%m')"
into a table
TABLE `app_logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`app` varchar(255) DEFAULT NULL,
`log_date` varchar(255) DEFAULT NULL,
`log_level` varchar(255) DEFAULT NULL,
`location` varchar(255) DEFAULT NULL,
`loc` varchar(255) DEFAULT NULL,
`message` text,
PRIMARY KEY (`id`)
)
To extend on MikeNereson's answer, here is a log4j.properties that worked:
I found the solution.
Replace the
PatternLayout
class with theEnhancedPatternLayout
class.org.apache.log4j.EnhancedPatternLayout
You'll also need to include the apache-log4j-extra dependency
Or include it in your pom:
You now have access to %throwable
I added to my table,
And updated my pattern to populate these columns.
Solution is we need to use EnhancedPattern Layout, by using this we can log the entire stack trace into DB. But there is one issue if we use this if the Stacktrace contain comma(,) , the message will not be get logged.I have solve this by over writing getLogStatement() which is available in JDBC appender Sourcecode
Follow the following steps
Download Log4j1.2.17. Enhanced patternlayout is available from log41.2.16 ver
Edit log4j properties file
Now create a new class that will extend JDBCappender and overwrite
getLogStatement()
:log4j 1.2.16+ 's EnhancedPatternLayout is not work! because it extends org.apache.log4j.Layout rather than org.apache.log4j.PatternLayout, but in JDBCAppender:
So if you use JDBCAppender like this:
will throw a ClassCastException in Point1:
EDIT (after in-depth research):
Use log4j.appender.JDBC.layout.ConversionPattern instead of log4j.appender.JDBC.sql, will avoid above ClassCastException:
and don't forget record the throwed exception to logger: