您的位置:首页 > 其它

RandomAccessFile读取远程系统日志

2016-08-03 00:00 375 查看
在某些特定的环境里,没有终端,没有控制台,想看到系统运行日志就比麻烦了,然后自己就写个Servlet方法来读取服务器运行日志,这样就省得麻烦管理员了。

public void getCatalinaLog(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

String v_pos = request.getParameter("v_pos"); //记取最后几个字节,默认10240

String log_file = request.getParameter("log_file");

String auto_refresh = request.getParameter("auto_refresh");

RandomAccessFile rf = null;

long pos ;

int i_pos = 0;

String catalina_home =System.getProperty("catalina.home");

String res = "";

String htmlstr = "";

String script = "";

if(log_file==null)

log_file = "/logs/proxool.log";

htmlstr += "<form action=common.do method=post name=form>";

htmlstr += "读取日志文件:<select name=log_file>";

htmlstr +="<option value=/logs/proxool.log >proxool</option>";

htmlstr +="<option value=/logs/catalina.out "+((log_file.indexOf("catalina")!=-1)?"selected":"")+">catalina</option></select>";

htmlstr += "  文件读取长度:<input name=v_pos value=:i_pos:>";

htmlstr += "  自动刷新:<input type=checkbox name=auto_refresh value=1 "+(auto_refresh!=null?"checked":"")+">";

htmlstr +="  <input type=hidden name=task value=getCatalinaLog onchange='exec_func()'><input type=submit>";

htmlstr += "</form>";

script +="<script>onload = function() {window.setInterval(exec_func, 5000);} ; ";

script +=" function exec_func(){if(document.form.auto_refresh.checked==true)document.form.submit();}; </script>";

htmlstr +=script;

try {

if(v_pos!=null) i_pos=Integer.parseInt(v_pos);

else i_pos = 10240;

htmlstr = htmlstr.replace(":i_pos:", String.valueOf(i_pos));//记录输入的值

rf=new RandomAccessFile(catalina_home +log_file,"r");

pos = rf.length();

if(pos>i_pos) pos = pos-i_pos;

else pos = pos-pos;

rf.seek(pos);//读取最后10K

String Line=rf.readLine();

while(Line!=null){

Line = new String(Line.getBytes("iso-8859-1"),System.getProperty("file.encoding"));

res+=(Line + "<br>");

Line=rf.readLine();

}

rf.close();//关闭文件流

Share.printWriter(htmlstr+res, response);

} catch (Exception e) {

htmlstr = htmlstr.replace(":i_pos:", String.valueOf(i_pos));//记录输入的值

Share.printWriter(htmlstr+res, response);

e.printStackTrace();

if(rf!=null)

try {

rf.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

如果服务端是win环境,需要修改启动脚本startup.bat里倒数第二行改为:call "%EXECUTABLE%" run %CMD_LINE_ARGS% > ../logs/catalina.out;这样才会把日志写入文件.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: