亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java如何將控制臺(tái)輸出日志寫入到指定文件中

 更新時(shí)間:2024年04月24日 10:55:44   作者:彭先生吖  
這篇文章主要介紹了java如何將控制臺(tái)輸出日志寫入到指定文件中問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

java將控制臺(tái)輸出日志寫入到指定文件中

設(shè)置控制臺(tái)日志輸出方式

/**
 * 控制臺(tái)日志寫入文件
 * @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;
    }
	
	//重寫輸出流的方式,改為兩種,一種控制臺(tái)輸出,一種寫入指定文件
	@Override
	public void write(int b) throws IOException {
		oldOutputStream.write(b);
		newOutputStream.write(b);
	}

	//當(dāng)前bean初始化前調(diào)用
	@PostConstruct
	public void writeLogToFile() throws Exception {
		File tmplLogFile = new File(getUploadPath(consoleLogWriteLinuxUrl, consoleLogWriteWindowsUrl));
		//啟一個(gè)定時(shí)線程延遲15分鐘后每過(guò)30分鐘檢查文件大小是否超過(guò)100M,如果超過(guò)則刪除重新創(chuàng)建
		ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
		executorService.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				try {
					//文件不存在就創(chuàng)建
			        if (!tmplLogFile.exists()) {
			            try {
							tmplLogFile.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
			        }
					//文件大于100M就刪除,重新創(chuàng)建
			        double KB = 1024 * 1024;
			        double MB = KB * 1024;
			        if(tmplLogFile.length() > MB * 100){
			            tmplLogFile.delete();
			        }
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 15, 30, TimeUnit.MINUTES);
		//設(shè)置輸出模式
        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));
	}
	
	/**
     * 根據(jù)當(dāng)前系統(tǒng)返回對(duì)應(yīng)的路徑 
     * @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;
    }
	
}

前端調(diào)用接口獲取最新日志信息

@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) {
			//將每一行的數(shù)據(jù)都存入集合中,統(tǒng)一返回
			result.add(new String(randomAccessFile.readLine().getBytes("ISO8859-1")));		
		}
		lastTimeFileSize = randomAccessFile.length();
		return genSuccessResult(result);
		
	}

}

java中自定義日志輸出到指定文件

創(chuàng)建一個(gè)類,以便調(diào)用方法,類名自定義,我這里定義類名是: WrittenLog

1.定義一個(gè)固定的路徑

private static final String fileXml = "C:/Users/zhangjie/Desktop/loger/loger";

2.定義一個(gè)字符串寫入的方法

其中有兩個(gè)參數(shù):

  • 一個(gè)是絕對(duì)路徑(fileXml)
  • 一個(gè)是傳入的字段串(context)
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
//把參數(shù)寫入日志文件
    private void logger (String context,String fileXml) throws IOException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String trace = sdf.format(new Date().getTime());定義一個(gè)系統(tǒng)時(shí)間
        File file = new File(fileXml);
        if (!file.exists()) {檢測(cè)是否有l(wèi)ogger.TXT文件
            file.mkdir();
        }
        
        String path = file+".txt";
        File writeFile = new File(path);
        if (!writeFile.exists()) {檢測(cè)是否在該路徑下有l(wèi)ogger文件夾
            writeFile.createNewFile();
            writeFile = new File(path);
        }
        FileOutputStream fw = new FileOutputStream(writeFile,true);
        Writer out = new OutputStreamWriter(fw,"UTF-8");設(shè)置字符集編碼格式
        out.write(trace+"----"+context);
        String newFile = System.getProperty("line.separator");
        out.write(newFile);
        out.close();
            fw.flush();
        fw.close();
                下列是xml格式的參數(shù)匹配,如果是json格式參數(shù)無(wú)需下列代碼
        Pattern p = Pattern.compile(">(\\s*|\n|\t|\r)<");  
        Matcher m = p.matcher(response);  
        String returnxml = m.replaceAll("><");  
        DocumentBuilderFactory builderFactory =         DocumentBuilderFactory.newInstance();
        Document doc = null;
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        if(returnxml!=null){
            StringReader sr = new StringReader(returnxml);
            InputSource is = new InputSource(sr);
            doc = builder.parse(is);
        }else{
            throw new Exception("沒(méi)有收款單數(shù)據(jù)傳入!");
        }
    }

3.創(chuàng)建實(shí)例,調(diào)用方法

WrittenLog write = new WrittenLog();
write.logger(context,fileXml);

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論