java如何将控制台输出日志写入到指定文件中
作者:彭先生吖
这篇文章主要介绍了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,如果超过则删除重新创建 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; } }
前端调用接口获取最新日志信息
@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中自定义日志输出到指定文件
创建一个类,以便调用方法,类名自定义,我这里定义类名是: 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());定义一个系统时间 File file = new File(fileXml); if (!file.exists()) {检测是否有logger.TXT文件 file.mkdir(); } String path = file+".txt"; File writeFile = new File(path); if (!writeFile.exists()) {检测是否在该路径下有logger文件夹 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.创建实例,调用方法
WrittenLog write = new WrittenLog(); write.logger(context,fileXml);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。