java将控制台输出日志写入到指定文件中

java将控制台输出日志写入到指定文件中_第1张图片
1、设置控制台日志输出方式

/**
 * 控制台日志写入文件
 * @author Mr peng
 *
 */
@Component
public class ConsoleLogWrite extends OutputStream{
	
	//window输出文件路径
	@Value("${consoleLogWrite.windowsUrl}")
	private String consoleLogWriteWindowsUrl;
	//linux输出文件路径
	@Value("${consoleLogWrite.linuxUrl}")
	private String consoleLogWriteLinuxUrl;
	
	private OutputStream oldOutputStream, newOutputStream;
	
	public ConsoleLogWrite() {
		
	}
	
	public ConsoleLogWrite(OutputStream oldOutputStream, OutputStream newOutputStream) {
        this.oldOutputStream = oldOutputStream;
        this.newOutputStream = newOutputStream;
    }
	
	//重写输出流的方式,改为两种,一种控制台输出,一种写入指定文件
	@Override
	public void write(int b) throws IOException {
		oldOutputStream.write(b);
		newOutputStream.write(b);
	}

	//当前bean初始化前调用
	@PostConstruct
	public void writeLogToFile() throws Exception {
		File tmplLogFile = new File(getUploadPath(consoleLogWriteLinuxUrl, consoleLogWriteWindowsUrl));
		//启一个定时线程延迟15分钟后每过30分钟检查文件大小是否超过100M,如果超过则删除重新创建
		ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
		executorService.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				try {
					//文件不存在就创建
			        if (!tmplLogFile.exists()) {
			            try {
							tmplLogFile.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
			        }
					//文件大于100M就删除,重新创建
			        double KB = 1024 * 1024;
			        double MB = KB * 1024;
			        if(tmplLogFile.length() > MB * 100){
			            tmplLogFile.delete();
			        }
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 15, 30, TimeUnit.MINUTES);
		//设置输出模式
        PrintStream oldOutputStream = System.out;
        OutputStream newOutputStream = new FileOutputStream(tmplLogFile);
        ConsoleLogWrite multiOutputStream = new ConsoleLogWrite(oldOutputStream, new PrintStream(newOutputStream));
        System.setOut(new PrintStream(multiOutputStream));
        System.setErr(new PrintStream(multiOutputStream));
	}
	
	/**
     * 根据当前系统返回对应的路径 
     * @param linuxPath
     * @param windowsPath
     * @return
     */
    public static String getUploadPath(String linuxPath, String windowsPath) {
    	if(System.getProperty("os.name").toLowerCase().indexOf("linux") > 0) {
    		return linuxPath;
    	}
    	return windowsPath;
    }
	
}

2、前端调用接口获取最新日志信息

@RestController
@RequestMapping("/portal")
public class ConsoleLogReadRes extends BaseController{

	//window输出文件路径
	@Value("${consoleLogWrite.windowsUrl}")
	private String consoleLogWriteWindowsUrl;
	//linux输出文件路径
	@Value("${consoleLogWrite.linuxUrl}")
	private String consoleLogWriteLinuxUrl;	
	//记录日志文件最后的大小
	private long lastTimeFileSize = 0; 	

	@GetMapping("/getConsoleLogInfo")
	public BaseResultVO getConsoleLogInfo(){
		
		File tmplLogFile = new File(FileUtils.getUploadPath(consoleLogWriteLinuxUrl, consoleLogWriteWindowsUrl));
        List<String> result = new ArrayList<String>();
		RandomAccessFile randomAccessFile = new RandomAccessFile(tmplLogFile, "rw");
		randomAccessFile.seek(lastTimeFileSize);    //从上次日志文件后开始读取
		while (randomAccessFile.readLine() != null) {
			//将每一行的数据都存入集合中,统一返回
			result.add(new String(randomAccessFile.readLine().getBytes("ISO8859-1")));		
		}
		lastTimeFileSize = randomAccessFile.length();
		return genSuccessResult(result);
		
	}

}

你可能感兴趣的:(java,开发语言)