import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class TomcatMonitor {
	public static String host="127.0.0.1";
	public static String port="10001";
	public static String user="monitor";
	public static String pwd="adchina";
	public static String connector="\"http-bio-8080\"";
	public static String basepath="/monitordata";
	public static void main(String[] args) throws IOException{
		Parser(args);
		String jmxUrl="service:jmx:rmi:///jndi/rmi://"+host+":"+port+"/jmxrmi";
		int jvm_memory_free=0;
		int jvm_memory_max=0;
		int jvm_memory_total=0;
		
		int connector_max_time=0;
		int connector_error_count=0;
		int connector_bytes_sent=0;
		int connector_processing_time=0;
		int connector_request_count=0;
		int connector_bytes_received=0;
		
		int connector_current_thread_count=0;
		int connector_min_spare_threads=0;
		int connector_max_threads=0;
		int connector_max_spare_threads=0;
		int connector_current_threads_busy=0;
		JMXConnector jmxConnector =null;
		try {
			JMXServiceURL serviceURL=new JMXServiceURL(jmxUrl);
			Map<String,String[]> map=new HashMap<String,String[]>();
			String[] credentials = new String[] { user, pwd };
			map.put("jmx.remote.credentials", credentials); 
			jmxConnector = JMXConnectorFactory.connect(serviceURL, map);  
			MBeanServerConnection mbsc = jmxConnector.getMBeanServerConnection();
			ObjectName threadObjName = new ObjectName("Catalina:type=ThreadPool,name="+connector+"");
            connector_current_thread_count=Integer.parseInt(mbsc.getAttribute(threadObjName, "currentThreadCount").toString());
            connector_min_spare_threads=Integer.parseInt(mbsc.getAttribute(threadObjName, "minSpareThreads").toString());
            connector_max_threads=Integer.parseInt(mbsc.getAttribute(threadObjName, "maxThreads").toString());
            //if(mbsc.getAttribute(threadObjName, "maxSpareThreads")!=null)
            //	connector_max_spare_threads=Integer.parseInt(mbsc.getAttribute(threadObjName, "maxSpareThreads").toString());
            connector_current_threads_busy=Integer.parseInt(mbsc.getAttribute(threadObjName, "currentThreadsBusy").toString());
            
            ObjectName requestObjectName=new ObjectName("Catalina:type=RequestProcessor,worker=\"http-bio-8080\",name=HttpRequest1");
            connector_max_time=Integer.parseInt(mbsc.getAttribute(requestObjectName, "maxTime").toString());
            connector_error_count=Integer.parseInt(mbsc.getAttribute(requestObjectName, "errorCount").toString());
            connector_bytes_sent=Integer.parseInt(mbsc.getAttribute(requestObjectName, "bytesSent").toString());
            connector_processing_time=Integer.parseInt(mbsc.getAttribute(requestObjectName, "processingTime").toString());
            connector_request_count=Integer.parseInt(mbsc.getAttribute(requestObjectName, "requestCount").toString());
            connector_bytes_received=Integer.parseInt(mbsc.getAttribute(requestObjectName, "bytesReceived").toString());
            
            String output_str="jvm_memory_free:"+jvm_memory_free+" jvm_memory_max:"+jvm_memory_max+" jvm_memory_total:"+jvm_memory_total+
			        " connector_max_time:"+connector_max_time+" connector_error_count:"+connector_error_count+" connector_bytes_sent:"+connector_bytes_sent+" connector_bytes_received:"+connector_bytes_received+
			        " connector_processing_time:"+connector_processing_time+" connector_request_count:"+connector_request_count+" connector_current_thread_count:"+connector_current_thread_count+
			        " connector_min_spare_threads:"+connector_min_spare_threads+" connector_max_threads:"+connector_max_threads+" connector_max_spare_threads:"+connector_max_spare_threads+
			        " connector_current_threads_busy:"+connector_current_threads_busy;
			saveDataToFile(output_str);
		} catch (Exception e) {
			errorLog(e.getMessage());
		}
		finally
		{
			if(connector!=null)
			{
				try {
					jmxConnector.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void Parser(String[] args)
	{
		Map<String, String> opt=new HashMap<String,String>();
		for(int i=0;i<args.length;i++){
			if(args[i].equals("-h")||args[i].equals("--help"))
			{
				System.out.println("-h,--help  		show this help message and exit");
				System.out.println("-H HOST    		tomcat server host");
				System.out.println("-P PORT    		tomcat server port");
				System.out.println("-u USER    		jmx user");
				System.out.println("-p PWD          jmx password");
				System.out.println("--path BASEPATH data & log file base path");
				System.exit(0);
			}
			if(args[i].startsWith("-")&&(i+1)<args.length){
				opt.put(args[i], args[i+1]);
			}
		}
		host=opt.containsKey("-H")?opt.get("-H"):host;
		port=opt.containsKey("-P")?opt.get("-P"):port;
		user=opt.containsKey("-u")?opt.get("-u"):user;
		pwd=opt.containsKey("-p")?opt.get("-p"):pwd;
		connector=opt.containsKey("-c")?opt.get("-c"):connector;
		basepath=opt.containsKey("--path")?opt.get("--path"):basepath;
	}
	
	public static void saveDataToFile(String data_str) throws IOException
	{
		Date dt=new Date();
		String date= new SimpleDateFormat("yyyy.MM.dd").format(dt);
		String now=new SimpleDateFormat("HH.mm.ss").format(dt);
		String path=basepath+"/Tomcat/data/"+date+"/";
		File directory=new File(path);
		if(!directory.exists())
			directory.mkdirs();
		String filePath=path+now+".csv";
		File dataFile=new File(filePath);
		if(!dataFile.exists())
			dataFile.createNewFile();
		FileOutputStream fos = new FileOutputStream(filePath,true);
		fos.write(data_str.getBytes());
		fos.close();	
	}
	
	public static void errorLog(String mes) throws IOException{
		Date dt=new Date();
		String date= new SimpleDateFormat("yyyy.MM.dd").format(dt);
		String now=new SimpleDateFormat("HH:mm:ss").format(dt);
		String path=basepath+"/Tomcat/log/";
		File directory=new File(path);
		if(!directory.exists())
			directory.mkdirs();
		String filePath=path+date+".csv";
		File dataFile=new File(filePath);
		if(!dataFile.exists())
			dataFile.createNewFile();
		FileOutputStream fos = new FileOutputStream(filePath,true);
		fos.write(("["+now+"]:"+mes+"\r\n").getBytes());
		fos.close();
	}
}
原文:http://www.cnblogs.com/biboxie/p/4233371.html