MelonBlog

一个业务日志工具类

想把一些关键信息写到特定的文件里,所以写了一个文件工具类

代码

package utils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class FileLogUtils {
    private static final String logDir;
    private static final HashMap<String, Logger> fileMap;
    private static final ReentrantLock lock;
    static {
        logDir = System.getProperty("user.dir") + "/logs";
        fileMap = new HashMap<>();
        lock = new ReentrantLock();
    }
    /**
     * 获取文件输出流
     *
     * @author yehao
     */
    public static Logger getLogger(String category) {
        lock.lock();
        try {
            Logger logger = fileMap.get(category);
            if (logger == null) {
                logger = new Logger();
                logger.setCategory(category);
                logger.setLogDir(logDir);
                logger.setFilePath(logger.getLogDir() + '/' + category + ".log");
                File file = new File(logger.getFilePath());
                if (!file.exists()) {
                    if (file.createNewFile()) {
                        log.info("创建新文件");
                    }
                }
                logger.setFile(file);
                logger.setPrintWriter(new PrintWriter(new FileOutputStream(file, true), true));
                fileMap.put(category, logger);
            }
            return logger;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    @Data
    public static class Logger {
        private String category;
        private String logDir;
        private String filePath;
        private File file;
        private PrintWriter printWriter;
        public void info(String format, Object... log) {
            printWriter.println(String.format("[%s] - %s", FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(new Date()), String.format(format, log)));
            printWriter.flush();
        }
        public void info(String log) {
            printWriter.println(String.format("[%s] - %s", FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(new Date()), log));
            printWriter.flush();
        }
    }
    public static void main(String[] args) {
        Logger logger = FileLogUtils.getLogger("test");
        logger.info("test1: %s", "hello");
        logger.info("test2");
        logger.info("test3");
        logger.info("test4");
    }
}

友情链接


Copyright © 2023 www.tiangua.info 鄂ICP备2022015834号