根据指定路径增加文件

package org.springblade.common.config;

import com.alibaba.nacos.common.utils.StringUtils;
import org.springblade.common.dto.LogDto;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class LogEntry {
	private static final LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
	private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(
		50, // 核心线程数
		60, // 最大线程数
		1L, // 空闲线程存活时间
		TimeUnit.MILLISECONDS, // 时间单位
		taskQueue // 任务队列
	);

	private static final AtomicBoolean isRunning = new AtomicBoolean(false);

	// 将增加日志任务添加到任务队列
	public static synchronized void logToFile(LogDto logDto) {
		// 将日志消息封装成 Runnable 任务
		Runnable logTask = () -> writeLog(logDto);

		// 提交任务到线程池
		if (isRunning.compareAndSet(false, true)) {
			executor.submit(() -> processLogs());
		}

		taskQueue.offer(logTask);
	}

	// 执行线程池中的任务
	private static void processLogs() {
		while (true) {
			try {
				Runnable task = taskQueue.poll(1, TimeUnit.SECONDS);
				if (task == null) {
					break; // 队列为空,退出循环
				}
				task.run(); // 执行任务
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				break;
			} catch (Exception e) {
				System.err.println("写入日志时发生异常: " + e.getMessage());
				e.printStackTrace();
			}
		}
		isRunning.set(false); // 标记任务已完成
	}

	// 创建文件夹并增加日志信息
	public static  synchronized void writeLog(LogDto logDto) {
		String relativeFolderPath = logDto.getRelativeFolderPath();
		String fileName = logDto.getFileName();
		String logMessage = logDto.getLogMessage();

		File folder = new File(relativeFolderPath);

		// 如果文件夹不存在,则创建
		if (!folder.exists()) {
			folder.mkdirs();
		}

		// 构建完整的文件路径
		File file = new File(folder, fileName);

		// 如果文件不存在,则尝试创建
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				System.err.println("无法创建文件: " + e.getMessage());
				return;
			}
		}
		if (StringUtils.isNotEmpty(logMessage)) {
			// 向文件中追加日志信息
			try (FileWriter writer = new FileWriter(file, true)) { // 'true' 表示追加模式
				writer.write(logMessage + "\n\n");
			} catch (IOException e) {
				System.err.println("写入文件时出错: " + e.getMessage());
			}
		}
	}

}
@Data
public class LogDto {
	/**
	 * 文件夹
	 */
	private String relativeFolderPath;

	/**
	 * 文件名称
	 */
	private String fileName;
	/**
	 * 日志信息
	 */
	private String logMessage;
}

步骤:1.判断指定的文件与文件名是否存在

2.若存在则添加信息,若不存在则创建文件夹和文件名

3.使用线程池调用创建方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值