appengineのアプリケーションログをチェックして、ERRORレベルのログがあった場合、管理者にメールで通知するプログラムを作ってみました。
Servletで作ってcronで実行します。


public class LogWatchServlet extends HttpServlet {
    
    private final static Log log = LogFactory.getLog(LogWatchServlet.class);
    
    private final static long duration = 20 * 60 * 1000; // 20min
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+9:00"));
        
        LogQuery query = LogQuery.Builder
            .withDefaults()
            .minLogLevel(LogLevel.ERROR)
            .majorVersionIds(Arrays.asList(new String[]{SystemProperty.applicationVersion.get().split("\\.")[0]}))
            .includeAppLogs(true)
            .startTimeMillis(System.currentTimeMillis() - duration);
        
        log.debug("log watch version: " + SystemProperty.applicationVersion.get());
        
        // ログ取得
        String lastOffset = null;
        List<RequestLogs> logs = new ArrayList<RequestLogs>();
        do {
            if (lastOffset != null) {
                query.offset(lastOffset);
            }
            int count = 0;
            for (RequestLogs record : LogServiceFactory.getLogService().fetch(query)) {
                logs.add(record);
                lastOffset = record.getOffset();
                count++;
            }
            if (count == 0) {
                break;
            }
        } while(true);
        
        // ログがあったらメール送信
        if (! logs.isEmpty()) {
            List<String> logbuffer = new ArrayList<String>();
            int i=0;
            for (RequestLogs record: logs) {
                logbuffer.add(format.format(new Date(record.getEndTimeUsec()/1000)) + " " + record.getResource());
                for (AppLogLine line: record.getAppLogLines()) {
                    if (line.getLogLevel().compareTo(LogLevel.ERROR) >= 0) {
                        logbuffer.add(" " + line.getLogMessage());
                    }
                }
                if (i > 50) {
                    break;
                }
                i++;
            }
            logbuffer.add("\n\n全" + logs.size() + "件");
            
            // メール送信
            MailService mailService = MailServiceFactory.getMailService();
            String sender = "admin@" + AppConst.appId() + ".appspotmail.com";
            String subject = "[" + AppConst.appId() + "] applicaton log notification";
            MailService.Message message = new MailService.Message(sender, null, subject, StringUtils.join(logbuffer, "\n"));
            mailService.sendToAdmins(message);
        }
        
        return;
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        doGet(request, response);
    }

}


コメントは受け付けていません。