简易日志工具类

依赖 

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.7</version>
</dependency>

代码

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;

import javax.swing.filechooser.FileSystemView;

/**
 * 默认输出到 windows 桌面 log4dev 目录下,以日期命名;
 * 配合监视工具实时查看日志;
 * @author bo
 */
public class LogPart {

    private static String dir;
    private static FileWriter fileWriter;

    static {
        if (shouldWork()){
            String desktop = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
            if (StrUtil.isEmpty(dir)) dir = desktop + "\\log4dev\\";
            String date = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
            String fileName = date + ".log";
            String path = dir + fileName;
            fileWriter = new FileWriter(path);
        }
    }

    public static void log(String format,Object...info){
        if (!shouldWork()) return;
        try {
            String formatLog = formatLog(format, info);
            fileWriter.append(formatLog);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    private static String formatLog(String format,Object...info){
        String dateTime = DateUtil.format(DateUtil.date(), "HH:mm:ss.SSS");
        String threadInfo = "[" + Thread.currentThread().getName() + "-" + Thread.currentThread().getId() + "]";
        // getStackTrace formatLog log
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        int layer = 3;
        if (stackTrace.length - 1 < layer) layer = stackTrace.length - 1;
        String className = stackTrace[layer].getClassName();
        String methodName = stackTrace[layer].getMethodName();
        int lineNumber = stackTrace[layer].getLineNumber();
        String logContent = StrUtil.format(format, info);
        String log = StrUtil.format("{} {} {}.{}@{} - {}\n"
                ,dateTime,threadInfo,className,methodName,lineNumber,logContent);
        return log;
    }

    private static boolean shouldWork() {
        if (SystemUtil.getOsInfo().isWindows()){
            return true;
        } else {
            return false;
        }
    }
}

 

posted on 2022-03-03 12:35  guardianbo  阅读(111)  评论(0编辑  收藏  举报

导航