使用Java自己DIY一个日志框架

前言
在开发过程中我们经常会用到某种日志框架去处理日志信息,下面是我自己DIY的一个日志框架,请各位看官老爷鉴赏,如有不足,望谅解。


配置文件
log.properties

log.level=DEBUG
log.file=logs/log-%date%.log
log.pattern=%date%---[%level%]---%class%: %message%

核心实现
Logger.java

package org.example.logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Logger {

    private final String pattern;

    private final String logFilePath;

    private final String level;

    @SuppressWarnings("rawtypes")
    private Class clazz;

    private static final Map<String, Integer> leveMap = new HashMap<>();

    static {
        leveMap.put("DEBUG", 1);
        leveMap.put("INFO", 2);
        leveMap.put("WARN", 3);
        leveMap.put("ERROR", 4);
        leveMap.put("CRITICAL", 5);
        leveMap.put("None", 6);
    }

    private static Logger logger;

    private static String configPath;

    private Logger() {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(Logger.configPath));
            level = properties.getProperty("log.level");
            pattern = properties.getProperty("log.pattern");
            logFilePath = properties.getProperty("log.file").replace("%date%", getLogDate("yyyy-MM-dd"));;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void configuration(String configPath) {
        Logger.configPath = configPath;
        logger = new Logger();
    }


    @SuppressWarnings("rawtypes")
    public static Logger getLogger(Class clazz) {
        if (configPath == null || configPath.trim().isEmpty()) {
            configPath = "config/log.properties";
            logger = new Logger();
        }
        logger.clazz = clazz;
        return logger;
    }


    public void debug(String message) {
        if (leveMap.get(level) > 1) {
            return;
        }
        System.out.println(logger(message, "DEBUG"));
        checkAndCreateLogfile();
        logWriter(logger(message, "DEBUG"));
    }

    public void debug(String format, Object... o) {
        if (leveMap.get(level) > 1) {
            return;
        }
        System.out.println(logger(String.format(format, o), "DEBUG"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(String.format(format, o), "DEBUG"));
        }
    }

    public void info(String message) {
        if (leveMap.get(level) > 2) {
            return;
        }
        System.out.println(logger(message, "INFO"));
        if(checkAndCreateLogfile()){
            logWriter(logger(message, "INFO"));
        }
    }


    public void info(String format, Object... o) {
        if (leveMap.get(level) > 2) {
            return;
        }
        System.out.println(logger(String.format(format, o), "INFO"));
        if(checkAndCreateLogfile()) {
            logWriter(logger(String.format(format, o), "INFO"));
        }
    }

    public void warn(String message) {
        if (leveMap.get(level) > 3) {
            return;
        }
        System.out.println(logger(message, "WARN"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(message, "WARN"));
        }
    }

    public void warn(String format, Object... o) {
        if (leveMap.get(level) > 3) {
            return;
        }
        System.out.println(logger(String.format(format, o), "WARN"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(String.format(format, o), "WARN"));
        }
    }

    public void error(String message) {
        if (leveMap.get(level) > 4) {
            return;
        }
        System.err.println(logger(message, "ERROR"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(message, "ERROR"));
        }
    }

    public void error(String format, Object... o) {
        if (leveMap.get(level) > 4) {
            return;
        }
        System.err.println(logger(String.format(format, o), "ERROR"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(String.format(format, o), "ERROR"));
        }
    }

    public void error(String format, Throwable t, Object... o) {
        if (leveMap.get(level) > 4) {
            return;
        }
        System.err.println(logger(String.format(format, o), "ERROR"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(String.format(format, o), "ERROR"));
        }
        for (StackTraceElement stackTraceElement : t.getStackTrace()) {
            System.err.println(stackTraceElement);
            logWriter(stackTraceElement.toString());
        }
    }

    public void critical(String message) {
        if (leveMap.get(level) > 5) {
            return;
        }
        System.err.println(logger(message, "CRITICAL"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(message, "CRITICAL"));
        }
    }

    public void critical(String format, Object... o) {
        if (leveMap.get(level) > 4) {
            return;
        }
        System.err.println(logger(String.format(format, o), "CRITICAL"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(String.format(format, o), "CRITICAL"));
        }
    }

    public void critical(String format, Throwable t, Object... o) {
        if (leveMap.get(level) > 4) {
            return;
        }
        System.err.println(logger(String.format(format, o), "CRITICAL"));
        if (checkAndCreateLogfile()) {
            logWriter(logger(String.format(format, o), "CRITICAL"));
        }
        for (StackTraceElement stackTraceElement : t.getStackTrace()) {
            System.err.println(stackTraceElement);
            logWriter(stackTraceElement.toString());
        }
    }

    private String logger(String message, String level) {
        return pattern.replace("%date%", getLogDate())
                .replace("%class%", clazz.getName())
                .replace("%level%", level)
                .replace("%message%", message);
    }

    private String getLogDate() {
        LocalDateTime now = LocalDateTime.now();
        return now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    }

    private String getLogDate(String pattern) {
        LocalDateTime now = LocalDateTime.now();
        return now.format(DateTimeFormatter.ofPattern(pattern));
    }

    private boolean checkAndCreateLogfile() {
        File file = new File(logFilePath);
        if (!file.exists()) {
            File parentFile = file.getParentFile();
            //noinspection ResultOfMethodCallIgnored
            parentFile.mkdirs();
            try {
                return file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }

    private void logWriter(String log) {
        try {
            PrintWriter printWriter = new PrintWriter(new FileWriter(logFilePath, true));
            printWriter.println(log);
            printWriter.flush();
            printWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

你可能感兴趣的:(Java之路,java,jvm,开发语言,架构)