Log4j JDBCAppender to log stacktraces

前端 未结 4 1666
醉酒成梦
醉酒成梦 2021-01-06 23:52

Using org.apache.log4j.jdbc.JDBCAppender, how can I get stracktraces logged with warn and error into the PatternLayout.

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 00:06

    I found the solution.

    Replace the PatternLayout class with the EnhancedPatternLayout class.

    org.apache.log4j.EnhancedPatternLayout

    You'll also need to include the apache-log4j-extra dependency

    Or include it in your pom:

    
      log4j
      apache-log4j-extras
      1.1
    
    

    You now have access to %throwable

    %throwable{short} or %throwable{1} will output the first line of stack trace. throwable{none} or throwable{0} will suppress the stack trace. %throwable{n} will output n lines of stack trace if a positive integer or omit the last -n lines if a negative integer.

    I added to my 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,
      `throwable` text,
      `stacktrace` text,
      PRIMARY KEY (`id`)
    )
    

    And updated my pattern to populate these columns.

    "INSERT INTO app_logs (app, log_date, log_level, location, loc, message, throwable, stacktrace) VALUES ('my-apps-name', '%d{ISO8601}','%p', '%C.java', '%C{1}.java:%L', '%m', '%throwable{short}', '%throwable{100}')"
    

提交回复
热议问题