www.zhblog.net

Java原生logging根据天生成日志

目标:使用原生logging,像NGINX日志那样,每天生成一个新的日志文件。如:logs.log-20210406


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.logging.*;

public class LoggerUtil {
    private static final Logger logger = Logger.getLogger(LoggerUtil.class.getName());

    public static Logger getLogger() {
        String openfireHome = JiveGlobals.getHomeDirectory();       
        String day = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String logPath = openfireHome + File.separator + "logs" + File.separator + "lk.log-" + day;
        System.out.println(logPath);
        if (!Files.exists(Paths.get(logPath)) || logger.getHandlers().length == 0) {
            init(logPath);
        }
        return logger;
    }

    private static void init(String logPath) {
        try {
            for (Handler handler : logger.getHandlers()) {
                handler.close();
                logger.removeHandler(handler);
            }

            logger.setLevel(Level.INFO);
            FileHandler handler = new FileHandler(logPath, true);
            SimpleFormatter formatter = new SimpleFormatter();
            handler.setFormatter(formatter);
            handler.setLevel(Level.INFO);
            logger.addHandler(handler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void error(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        getLogger().warning(sw.toString());
    }

}

 

error方法是使用Java原生记录error栈信息,这样方便排查异常。

 

展开阅读全文

评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 心情