欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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);

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • 阿里云主機上安裝jdk 某庫出現問題的解決方法

    阿里云主機上安裝jdk 某庫出現問題的解決方法

    今天安裝jdk到阿里云服務上,首先看下阿里云是32位還是64位的,如果是32位下載32位的包,如果是64位的下載64位的包,下面與大家分享下安裝過程中遇到問題的解決方法
    2013-06-06
  • IDEA報錯:java:無效的源發(fā)行版21解決方式

    IDEA報錯:java:無效的源發(fā)行版21解決方式

    這篇文章主要給大家介紹了關于IDEA報錯:java:無效的源發(fā)行版21的解決方式,這個錯誤是因為你的項目使用的Java版本與你的IDEA使用的Java版本不一致導致的,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2024-06-06
  • idea生成WebServices接口的完整流程步驟

    idea生成WebServices接口的完整流程步驟

    因為工作需要,數據傳輸部分需要使用webservice實現,經過兩天的研究,實現了一個簡單的例子,這篇文章主要給大家介紹了關于idea生成WebServices接口的完整流程步驟,需要的朋友可以參考下
    2024-08-08
  • SpringBoot啟動時加載指定方法的方式小結

    SpringBoot啟動時加載指定方法的方式小結

    本文主要給大家介紹了Spring Boot項目啟動時加載指定方法都有哪些方式的,文中給大家介紹了五種常用的方式,有詳細的代碼示例,具有一定的參考價值,需要的朋友可以參考下
    2023-08-08
  • JAVA編程實現隨機生成指定長度的密碼功能【大小寫和數字組合】

    JAVA編程實現隨機生成指定長度的密碼功能【大小寫和數字組合】

    這篇文章主要介紹了JAVA編程實現隨機生成指定長度的密碼功能,可生成帶有大小寫和數字組合的隨機字符串,需要的朋友可以參考下
    2017-07-07
  • Java 中synchronize函數的實例詳解

    Java 中synchronize函數的實例詳解

    這篇文章主要介紹了Java 中synchronize函數的實例詳解的相關資料,希望通過本文能幫助到大家理解使用synchronize函數的使用方法,需要的朋友可以參考下
    2017-09-09
  • Javascript和Java語言有什么關系?兩種語言間的異同比較

    Javascript和Java語言有什么關系?兩種語言間的異同比較

    雖然Javascript與Java有緊密的聯系,但卻是兩個公司開發(fā)的不同的兩個產品。那么js和java有什么關系,兩種語言的不同點是什么呢?介于這兩個問題,小編一起給大家解答下
    2016-09-09
  • Java日常練習題,每天進步一點點(27)

    Java日常練習題,每天進步一點點(27)

    下面小編就為大家?guī)硪黄狫ava基礎的幾道練習題(分享)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望可以幫到你
    2021-07-07
  • Spring AspectJ AOP框架注解原理解析

    Spring AspectJ AOP框架注解原理解析

    這篇文章主要介紹了Spring AspectJ AOP框架注解原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-09-09
  • Java中的Random()函數及兩種構造方法

    Java中的Random()函數及兩種構造方法

    Java中存在著兩種Random函數分別是java.lang.Math.Random和java.util.Random,文中給大家介紹了random()的兩種構造方法,感興趣的朋友跟隨小編一起看看吧
    2018-11-11

最新評論