java如何將控制臺輸出日志寫入到指定文件中
更新時間:2024年04月24日 10:55:44 作者:彭先生吖
這篇文章主要介紹了java如何將控制臺輸出日志寫入到指定文件中問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
java將控制臺輸出日志寫入到指定文件中
設置控制臺日志輸出方式
/** * 控制臺日志寫入文件 * @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,如果超過則刪除重新創(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); //設置輸出模式 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)); } /** * 根據當前系統(tǒ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; } }
前端調用接口獲取最新日志信息
@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) { //將每一行的數據都存入集合中,統(tǒng)一返回 result.add(new String(randomAccessFile.readLine().getBytes("ISO8859-1"))); } lastTimeFileSize = randomAccessFile.length(); return genSuccessResult(result); } }
java中自定義日志輸出到指定文件
創(chuàng)建一個類,以便調用方法,類名自定義,我這里定義類名是: WrittenLog
1.定義一個固定的路徑
private static final String fileXml = "C:/Users/zhangjie/Desktop/loger/loger";
2.定義一個字符串寫入的方法
其中有兩個參數:
- 一個是絕對路徑(fileXml)
- 一個是傳入的字段串(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; //把參數寫入日志文件 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());定義一個系統(tǒng)時間 File file = new File(fileXml); if (!file.exists()) {檢測是否有l(wèi)ogger.TXT文件 file.mkdir(); } String path = file+".txt"; File writeFile = new File(path); if (!writeFile.exists()) {檢測是否在該路徑下有l(wèi)ogger文件夾 writeFile.createNewFile(); writeFile = new File(path); } FileOutputStream fw = new FileOutputStream(writeFile,true); Writer out = new OutputStreamWriter(fw,"UTF-8");設置字符集編碼格式 out.write(trace+"----"+context); String newFile = System.getProperty("line.separator"); out.write(newFile); out.close(); fw.flush(); fw.close(); 下列是xml格式的參數匹配,如果是json格式參數無需下列代碼 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("沒有收款單數據傳入!"); } }
3.創(chuàng)建實例,調用方法
WrittenLog write = new WrittenLog(); write.logger(context,fileXml);
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
JAVA編程實現隨機生成指定長度的密碼功能【大小寫和數字組合】
這篇文章主要介紹了JAVA編程實現隨機生成指定長度的密碼功能,可生成帶有大小寫和數字組合的隨機字符串,需要的朋友可以參考下2017-07-07Javascript和Java語言有什么關系?兩種語言間的異同比較
雖然Javascript與Java有緊密的聯系,但卻是兩個公司開發(fā)的不同的兩個產品。那么js和java有什么關系,兩種語言的不同點是什么呢?介于這兩個問題,小編一起給大家解答下2016-09-09