All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.doudou.common.tool.aspect.WriteLogToFile Maven / Gradle / Ivy

There is a newer version: 1.3.2
Show newest version
package top.doudou.common.tool.aspect;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import top.doudou.base.stream.StreamCloseUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author  傻男人<[email protected]>
 * @Date: 2020/8/19 9:20
 * @Version: 1.0
 * @Description: 将日志写入文件中
 */
@Slf4j
public class WriteLogToFile implements Serializable {

    private static ExecutorService LOG_POOL = new ThreadPoolExecutor(9, 36,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue(256),
            new ThreadFactoryBuilder().setNameFormat("log-write-pool-%d").build(),
            new ThreadPoolExecutor.AbortPolicy());

    /**
     * 将日志写入文件中
     * @param file 文件
     * @param log  内容
     * @param flag  是否添加日志开头的日志的时间
     */
    public static void logToFile(String file,String log,boolean flag){
        checkFile(file);
        FileOutputStream outputStream = null;
        FileChannel fileChannel = null;
        try{
            outputStream = new FileOutputStream(file,true);
            fileChannel = outputStream.getChannel();
            String res = logTime() +"   "+ log;
            String lineBreak = getLineBreak();
            writeCommonLog(fileChannel,flag ? logTime() +"    "+ log : log,lineBreak);
        }catch (IOException e){
            StreamCloseUtils.close(fileChannel);
            StreamCloseUtils.close(outputStream);
        }
    }

    public static void logToFile(String file,String log){
        logToFile(file,log,true);
    }

    public static void asyncLogToFile(String file,String log){
        LOG_POOL.execute(()->logToFile(file,log,true));
    }

    public static void asyncLogToFile(String file,String log,boolean flag){
        LOG_POOL.execute(()->logToFile(file,log,flag));
    }

    /**
     * 将日志写入文件中
     * @param file 文件
     * @param log  内容
     * @param flag  是否添加日志开头的日志的时间
     * @param exception  异常的信息
     */
    public static void logToFile(String file,String log,boolean flag,Exception exception){
        checkFile(file);
        FileOutputStream outputStream = null;
        FileChannel fileChannel = null;
        try{
            outputStream = new FileOutputStream(file,true);
            fileChannel = outputStream.getChannel();
            String res = logTime() +"   "+ log;
            String lineBreak = getLineBreak();
            ByteBuffer byteBuffer = writeCommonLog(fileChannel,flag ? logTime() +"    "+ log : log,lineBreak);
            if(null != exception){
                byteBuffer.flip();
                String exceptionMsg = exception.getClass().getName()+"  "+ exception.getLocalizedMessage();
                writeLogToFileChannel(fileChannel,byteBuffer,exceptionMsg,lineBreak);
                writeExceptionLog(fileChannel,exception,lineBreak);
            }
        }catch (IOException ioe){
            StreamCloseUtils.close(fileChannel);
            StreamCloseUtils.close(outputStream);
        }
    }

    public static void logToFile(String file,String log,Exception exception){
        logToFile(file,log,true,exception);
    }

    public static void asyncLogToFile(String file,String log,Exception exception){
        LOG_POOL.execute(()->logToFile(file,log,true,exception));
    }

    public static void asyncLogToFile(String file,String log,boolean flag,Exception exception){
        LOG_POOL.execute(()->logToFile(file,log,flag,exception));
    }

    /**
     * 打印通用日志
     * @param fileChannel
     * @param log
     * @param lineBreak
     */
    private static ByteBuffer writeCommonLog(FileChannel fileChannel, String log, String lineBreak){
        ByteBuffer byteBuffer = ByteBuffer.allocate(log.getBytes().length+lineBreak.getBytes().length);
        writeLogToFileChannel(fileChannel,byteBuffer,log,lineBreak);
        return byteBuffer;
    }

    private static void writeLogToFileChannel(FileChannel fileChannel,ByteBuffer byteBuffer,String log,String lineBreak){
        byteBuffer.put(log.getBytes());
        byteBuffer.put(lineBreak.getBytes());
        byteBuffer.flip();
        try {
            fileChannel.write(byteBuffer);
        }catch (IOException ioException){

        }
    }

    /**
     * 打印异常的信息
     * @param fileChannel 文件通道
     * @param e 异常信息
     * @param lineBreak 换行符
     */
    private static void writeExceptionLog(FileChannel fileChannel, Exception e, String lineBreak){
        StackTraceElement[] stackTrace = e.getStackTrace();
        if(stackTrace.length <= 0 ){
            return;
        }
        for (int i = 0; i < stackTrace.length; i++) {
            StackTraceElement item = stackTrace[i];
            String msg = "    at  "+item.getClassName()+"."+item.getMethodName()+"("+item.getFileName()+":"+item.getLineNumber()+")";
            ByteBuffer buffer = ByteBuffer.allocate(msg.getBytes().length+lineBreak.getBytes().length);
            buffer.put(msg.getBytes());
            buffer.put(lineBreak.getBytes());
            buffer.flip();
            try {
                fileChannel.write(buffer);
            }catch (IOException ioException){
                StreamCloseUtils.close(fileChannel);
            }
        }
    }

    /**
     * 日志前的时间
     * @return
     */
    private static String logTime(){
        return DateUtil.now();
    }

    private static void checkFile(String path){
        File file = new File(path);
        if(!file.exists()){
            FileUtil.touch(file);
        }
    }
    /**
     * 获取换行符
     * @return
     */
    private static String getLineBreak(){
        String property = System.getProperty("os.name");
        if(property.startsWith("Windows")){
            return "\r\n";
        }
        if(property.startsWith("Linux")){
            return "\n";
        }
        if(property.startsWith("Mac")){
            return "\r";
        }
        return "\r\n";
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy