摘要
在日常開發中,程式設計師需要經常查詢伺服器日誌來排查問題和除錯程式。如果是本地除錯還好,但專案一旦釋出到伺服器上,每次查日誌就很麻煩,而且日誌量巨大,有時我們無法找到我們需要的資訊。經常需要藉助第三方工具來執行此類操作。那麼我們可不可以在編輯器上執行程式碼就能完成相應的操作呢?
答案是肯定的!經過研究與測試,我總結了以下的方法,呼叫次服務就能執行相應的linux命令,無需麻煩借用第三方工具了,在同一個開發工具上就能完成所有的操作。接下來看看程式碼吧!
程式程式碼
一、寫一個對外提供的services(ReadLogServlet)
public class ReadLogServletextends SlingAllMethodsServlet { private static final LoggerLOG = LoggerFactory.getLogger(ReadLogServlet.class); @Override protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=utf-8;"); String jsonStr = HttpRequestUtil.getRequestJson(request); try { JSONObject jsonObject =new JSONObject(jsonStr); String commond = jsonObject.getString("command"); String result = executeLinuxCmd(commond); if (result ==null) { LOG.error("result null"); return; } try (PrintWriter printWriter = response.getWriter()) { printWriter.write(result); response.flushBuffer(); }catch (IOException e) { LOG.error("Response writer error:" + e.toString()); } }catch (JSONException e) { }catch (IOException io){ try (PrintWriter printWriter = response.getWriter()) { printWriter.write(io.getMessage()); response.flushBuffer(); }catch (IOException e) { LOG.error("Response writer error:" + e.toString()); } } } //核心程式碼 public String executeLinuxCmd(String cmd)throws IOException { //System.out.println("got cmd job : " + cmd); Runtime run = Runtime.getRuntime(); // Process process = run.exec(cmd); Process process = run.exec(new String[]{"/bin/sh","-c", cmd}); InputStream in = process.getInputStream(); BufferedReader bs =new BufferedReader(new InputStreamReader(in)); //List list = new ArrayList(); StringBuffer sf =new StringBuffer(); String result =null; while ((result = bs.readLine()) !=null) { //System.out.println("job result [" + result + "]"); //list.add(result); sf.append(result); sf.append("\n"); } in.close(); // process.waitFor(); process.destroy(); return sf.toString(); } }
二、使用postman呼叫ReadLogServlet(使用其他工具呼叫也可)
總結:
除了查詢日誌外,還可執行其他linux命令。大家可繼續優化發掘,如果有更好的意見和技術,歡迎留言探討哦!