今作っているJavaEEアプリですが、画面エラー発生時のログ出力を検討しました。ま、アプリケーションサーバであるWebLogicが勝手にログを出してくれますが、エラー以外にも勝手に出るので量が多くて見るのが辛いし、アプリとしては別途log4j2でロギングする方向にしているので、画面エラー発生時もlog4j出力に統一するという要件になります。WebLogicでlog4jとログを連携させるとかFilter使うとかいろいろやり方はありそうでしたが、画面個々に手を入れずに最も簡単なやり方は無いかなと考えたところ、画面エラー発生時はエラーページに遷移するようにしておいて、そのエラーページでログ出力させるという形にしてみます。
web.xml抜粋(今の所・・・)
1 2 3 4 5 6 7 8 9 10 11 12 |
<error-page> <exception-type>javax.servlet.ServletException</exception-type> <location>/errors/index.xhtml</location> </error-page> <error-page> <exception-type>javax.ejb.EJBException</exception-type> <location>/errors/index.xhtml</location> </error-page> <error-page> <error-code>403</error-code> <location>/errors/403.xhtml</location> </error-page> |
エラーページ用JSF管理Bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
@ManagedBean(name="errorPage") public class ErrorHander { protected static Logger logger=LogManager.getLogger(); private String message; /** エラーメッセージ出力 */ public String getMessage() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); String errorURI = (String) request.getAttribute("javax.servlet.error.request_uri"); message = (String)request.getAttribute("javax.servlet.error.message"); Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); logger.error("View Error URL={}", errorURI, throwable); return message; } public void setMessage(String message) { this.message = message; } } |
最後にweb.xmlで指定した/errors/index.xhtmlで、エラー内容は見せないように下記を忍ばせておけば、管理Beanのメソッドが実行されるという形になります。
1 |
<h:outputLabel id="execMsg" value="#{errorPage.message}" style="visibility:hidden;"/> |