简单日志记录,使用java.util.logging

jsp+servlet+JavaBean模式下,可以做个简单的日志记录,日志文件保存在服务器.(Tomcat)

package controller;

import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "test", urlPatterns = "/*")
public class MainServlet extends HttpServlet {

    private static final long serialVersionUID = 7922611206674042939L;
    private static final String slash = File.separator;
    private static final String LOG_PATH = slash + "pro.log";
    public Logger logger = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("container opening");
        try {
            logger = Logger.getLogger(MainServlet.class.getName());
            logger.setUseParentHandlers(false);
            logger.addHandler(new FileHandler(config.getServletContext()
                    .getRealPath(LOG_PATH)));
        } catch (Exception e) {
            System.out.println("testing");
            logger = Logger.getLogger(MainServlet.class.getName());
        }
    }

    @Override
    public void destroy() {
        System.out.println("container closed");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        try {
            String[] str = {};
            System.out.println(str[-1]);
        } catch (Exception e) {
            System.out.println(4);
            logger.log(Level.WARNING, "数组下标越界", e);
        }

    }

}

日志文件一般安全要求不高,不需要至于WEB-INF目录下,直接输入日志名会自动生成.
java.util.logging.FileHandler类有个重写的构造器,可选择是否追加记录.看具体需求.
相对于log4j有很多局限性,但适合小型项目的简单日志记录.

个人感觉很适合打桩使用,毕竟无需引入额外的jar包,将文件处理器修改为控制台处理器,取消日志本地化后,就可以随意打桩调式了.当项目部署时,调用

logger.setlevel(Level.OFF);

即可

点赞