java如何將控制臺(tái)輸出日志寫入到指定文件中
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)文章
阿里云主機(jī)上安裝jdk 某庫(kù)出現(xiàn)問(wèn)題的解決方法
今天安裝jdk到阿里云服務(wù)上,首先看下阿里云是32位還是64位的,如果是32位下載32位的包,如果是64位的下載64位的包,下面與大家分享下安裝過(guò)程中遇到問(wèn)題的解決方法2013-06-06IDEA報(bào)錯(cuò):java:無(wú)效的源發(fā)行版21解決方式
這篇文章主要給大家介紹了關(guān)于IDEA報(bào)錯(cuò):java:無(wú)效的源發(fā)行版21的解決方式,這個(gè)錯(cuò)誤是因?yàn)槟愕捻?xiàng)目使用的Java版本與你的IDEA使用的Java版本不一致導(dǎo)致的,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06SpringBoot啟動(dòng)時(shí)加載指定方法的方式小結(jié)
本文主要給大家介紹了Spring Boot項(xiàng)目啟動(dòng)時(shí)加載指定方法都有哪些方式的,文中給大家介紹了五種常用的方式,有詳細(xì)的代碼示例,具有一定的參考價(jià)值,需要的朋友可以參考下2023-08-08JAVA編程實(shí)現(xiàn)隨機(jī)生成指定長(zhǎng)度的密碼功能【大小寫和數(shù)字組合】
這篇文章主要介紹了JAVA編程實(shí)現(xiàn)隨機(jī)生成指定長(zhǎng)度的密碼功能,可生成帶有大小寫和數(shù)字組合的隨機(jī)字符串,需要的朋友可以參考下2017-07-07Java 中synchronize函數(shù)的實(shí)例詳解
這篇文章主要介紹了Java 中synchronize函數(shù)的實(shí)例詳解的相關(guān)資料,希望通過(guò)本文能幫助到大家理解使用synchronize函數(shù)的使用方法,需要的朋友可以參考下2017-09-09Javascript和Java語(yǔ)言有什么關(guān)系??jī)煞N語(yǔ)言間的異同比較
雖然Javascript與Java有緊密的聯(lián)系,但卻是兩個(gè)公司開發(fā)的不同的兩個(gè)產(chǎn)品。那么js和java有什么關(guān)系,兩種語(yǔ)言的不同點(diǎn)是什么呢?介于這兩個(gè)問(wèn)題,小編一起給大家解答下2016-09-09Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(27)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-07-07Java中的Random()函數(shù)及兩種構(gòu)造方法
Java中存在著兩種Random函數(shù)分別是java.lang.Math.Random和java.util.Random,文中給大家介紹了random()的兩種構(gòu)造方法,感興趣的朋友跟隨小編一起看看吧2018-11-11