Mailing Exception logs in a live Grails webapp

白昼怎懂夜的黑 提交于 2019-12-03 10:17:00

问题


I'd like my Grails web-app to send an e-mail for each exception that reaches the end-user.

Basically I'm looking for a elegant way to achieve something equivalent to:

  try {
      // ... all logic/db-access/etc required to render the page is executed here ...
  }
  catch (Exception e) {
      sendmail("exception@example.com", "An exception was thrown while processing a http-request", e.toString);
  }

回答1:


Turns out this exact question was answered on the Grails mailing list a couple of days ago.

The solution is to add the following to the log4j-section of Config.groovy:

log4j {
    ...
    appender.mail='org.apache.log4j.net.SMTPAppender'
    appender.'mail.To'='email@example.com'
    appender.'mail.From'='email@example.com'
    appender.'mail.SMTPHost'='localhost'
    appender.'mail.BufferSize'=4096
    appender.'mail.Subject'='App Error'
    appender.'mail.layout'='org.apache.log4j.PatternLayout'
    appender.'mail.layout.ConversionPattern'='[%r] %c{2} %m%n'
    rootLogger="error,stdout,mail"
    ...
    // rootLogger="error,stdout" (old rootLogger)
}

Plus adding sun-javamail.jar and activation.jar to the lib/-folder.




回答2:


Assuming you can do this from groovy, you'll want to use a logging framework such as log4j for this, which has loggers that can append log data to a database, send email, etc.




回答3:


You could also take a look at exceptionHandler mechanism provided by Grails; I find it very simple; yet powerful enough to take care of all my custom & clean exception handling needs. Haven't tested this approach with 1.1 so far; but works very well with 1.0.3.

class BootStrap {

   def exceptionHandler

   def init = { servletContext ->
      exceptionHandler.exceptionMappings =
        [ 'NoSuchFlowExecutionException' :'/myControler/myAction',
        'java.lang.Exception' : '/myController/generalAction']
   }

  def destroy = { }
}

Detailed blog here :

http://blog.bruary.net/2008/03/grails-custom-exception-handling.html



来源:https://stackoverflow.com/questions/635590/mailing-exception-logs-in-a-live-grails-webapp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!