---
title: "JavaMelody 开源的系统监控工具～"
author: "nirvana_blanks"
date: "2010-11-12T11:30:52Z"
tags: []
categories: ["企业架构"]
slug: "javamelody"
draft: false
lastmod: "2010-11-25T20:48:43Z"
id: 809629
url: "https://nirvana-blanks.iteye.com/blog/809629"
---

**1.背景介绍：**

      在项目中，我们经常需要关注生产环境的服务器运行状况，以及服务器的负载，以往我们经常去会使用一些命令去观察服务器的状态，然后去观测系统的log作对应的分析，这种方法虽然能够达到预期的目的，但是我们获得一些信息并不是很直观，所以有的时候并不能及时发现服务器的异常状态，最后导致服务中断。

      现在我们有了javaMelody,他能够在QA和实际运行生产环境监测Java或Java EE应用程序服务器。并以图表的形式显示：Java内存和Java CPU使用情况，用户Session数量，JDBC连接数，和http请求、sql请求、jsp页面与业务接口方法（EJB3、Spring、 Guice）的执行数量，平均执行时间，错误百分比等。图表可以按天，周，月，年或自定义时间段查看。

      **2. 安装及配置：**

      安装之前我们需要先拿到我们需要的一些东西:

      项目主页：[http://code.google.com/p/javamelody/](http://code.google.com/p/javamelody/ "javaMelody")

      假设现在我们服务器的一些安装路径如下：

```
  tomcat5     /usr/local/tomcat5  
```

      现在我们拿到了javamelody-1.20.0.zip，解压之～，得到文件列表如下：

```
  javamelody.jar
  javamelody.war
  jira-javamelody.jar
  jrobin-1.5.9.1.jar
```

       我们得到很多文件，但是我们只关心这几个：

       javamelody.war 看他的名字～～～XXXXX.war，估计已经猜到这是放到哪里的了～，好我们现在把他放到他应该放到的地方：

 

```
  sudo cp javamelody.war /usr/local/tomcat5/webapps/
```

       偶也！现在javaMelody已经安装完成了！！！好简单。。。NND也没啥嘛～～

       现在打开浏览器，地址栏输入：http://localhost:8081/javamelody/，你看到了什么？？告诉我你看到了什么？？

       不要告诉我你看到了404或者 500跟随着一大片堆栈异常。。。，如果你真看到了这些，我只能表示遗憾～你杯具了，从头再来一遍吧。(\*^\_\_^\*) ......

       现在我们从浏览器看到了一个“及黑”简陋的页面，里面神马都木有。。。你需要对自己说：浮云啊～～神马都是浮云。。。

 

                                                                **Add an application**

     **Name of application to monitor :**  **\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_URL(s) :\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_**

     URL(s) example : *http://myhost/myapp/* or *http://host1/myapp/,http://host2/myapp/*  

 

 

 

      以我very very poor的鹰文水平都能看明白，这是什么意思，你肯定也明白了：我需要添加一个需要监控的应用，对！！添加一个需要被监控的应用！好吧，我添加！

     我们在Name of application to monitor :那输入被监控的应用的名称，任意起只要你能看明白，在URL(s)：输入被监控应用的URL，假设我现在有意个应用叫做TestMonitor，输入：http://localhost:8081/TestMonitor/ 猛击“Add”按钮！！Oh ....No....，我们看到了一个提示框，如是说：“hava you configured JavaMelody in this application?” ，Have you ?? Hava you ?? 呃...不好意思，忘记了一件灰常重要的事情：

      现在我们需要配置一下那个被监控的应用～，打开/usr/local/tomcat5/webapps/TestMonitor/WEB-INF/web.xml

 

```
sudo vi /usr/local/tomcat5/webapps/TestMonitor/WEB-INF/web.xml
```

    在其中加入：

 

```
<filter>
		<filter-name>monitoring</filter-name>
		<filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>monitoring</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<listener>
		<listener-class>net.bull.javamelody.SessionListener</listener-class>
	</listener>  
```

 

   你应该明白了吧，我们还有javamelody.jar、jrobin-1.5.9.1.jar木有用到，

```
<filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
```

   引用的就是 javamelody.jar、jrobin-1.5.9.1.jar ，我们把他放到WEB-INF/lib下

  

```
sudo cp javamelody.jar jrobin-1.5.9.1.jar /usr/local/tomcat5/webapps/TestMonitor/WEB-INF/lib 
```

    重启tomcat。刷新浏览器：http://localhost:8081/javamelody/页面，重新输入刚才输入的Name 以及 URL ，再次猛击"Add" 按钮，浏览器提示：Application TestMonitor added，ok到现在我们已经把javaMelody安装完成了，也配置了一个很简单的web应用。

    我们从页面上看到了很多的图表：

   大伙先大概看一下整个页面都有啥。那十几个图很好理解，

 Used memory ：内存占用

 % CPU : CPU占用

 Http Sessions ：session总数

 Active threads ：活动的线程数

 Active jdbc connections、活动的JDBC链接数

 Used jdbc connections：使用的JDBC连接

 http hits per minute：http 每分钟请求次数

 http mean times (ms) ：http响应平均时间

 % of http errors ：http错误百分比

 Sql hits per minute : 每份中执行SQL

 Sql mean times : sql 平均时间

 % of sql errors ： sql error百分比

 % Garbage Collector time : GC时间百分比

 Threads count ：线程总数

 Loaded classes count ：加载的类数

 Used non heap memory ： 使用非堆内存

 Used physical memory ： 使用的物理内存

 Used swap space ：交换空间

 

### Statistics http - 1 day ： （http 统计）

Request :请求路径

% of cumulative time ：累计时间百分比

Hits：点击量

Mean time (ms)：平均时间

Max time (ms)：最大时间

Standard deviation ：标准差 ，还不太明白其含义，讨论一下

% of cumulative cpu time ：累计CPU time 百分比

Mean cpu time (ms) ：平均CPU时间

% of system errors ： 系统错误百分比

Mean size (Kb) : 数据量平均大小

 

Statistics http system errors ： http 系统错误统计

Error ： 错误名称（或 异常信息）

 

Statistics system errors logs ：系统错误统计日志

### System informations ： 服务器系统信息

### Threads ： 系统线程

 

**可选参数**  
      JavaMelody可以配置一些参数，按照如下的优先级。  
    * 在过滤器的初始化参数中配置  
          (web.xml file in the webapp), 如:

```
<filter>
          <filter-name>monitoring</filter-name>
  <filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
<init-param>
          <param-name>system-actions-enabled</param-name>
<param-value>true</param-value>
</init-param>
</filter>
```

 

\* 在webapp的 context parameters 配置使用前缀： javamelody. ：

```
<Context docBase="path_to/mywebapp.war" path="mywebapp" reloadable="false">
<Parameter name="javamelody.system-actions-enabled" value="true" override="false"/>
</Context>
```

 

    * 使用前缀javamelody配置在系统属性中  
       $CATALINA\_HOME/conf/catalina.properties):  
       -Djavamelody-system-actions-enabled=true

    参数： **system-actions-enabled** (为了安全起见默认为false )开启一些系统功能：garbage collector, http sessions, heap dump, memory histogram, process list, jndi tree, opened jdbc connections, database (near the bottom of reports). 

    **url-exclude-pattern** 使用正则表达式来排除一些URL

    **http-transform-pattern** 使用正则表达式排除URL后边的动态参数，可以合并某些请求的监控。

    **sql-transform-pattern** 使用正则表达式合并一些sql请求

    参数ejb-transform-pattern , spring-transform-pattern , guice-transform-pattern , error-transform-pattern , log-transform-pattern , job-transform-pattern , struts-transform-pattern and jsp-transform-pattern 可以合并ejb3 methods, spring methods, guice methods, http system errors, system error logs, names of jobs,  struts actions 和jsp pages

    参数：**displayed-counters** 可以修改statistics和graphics显示的统计项(默认http,sql,error,log). 所以默认显示的http、sql、error、log。struts, jsp, ejb, spring, guice 和 services会在使用的时候自动显示出来，所以参数**displayed-counters** 可以利用值如：“http,sql,ejb,spring”来隐藏一些统计项 。

    参数**log** 可以启用INFO级别的logs (默认为false). 使用当前应用内配置的Logback/log4j/java.util.logging记录http request的持续时间和大小，记录在以在应用内配置的过滤器的名称为文件名的日志文件内，

    参数**storage-directory** 是存储目录 (默认为javamelody). 如果目录以'/'开头,则认为是绝对路径, 否则会被认为是相对于temp的相对路径(&lt;temp&gt; in TOMCAT\_HOME for tomcat). 如果要修改这个参数，推荐同时重命名真实的物理路径。

    参数**resolution-seconds** 可以配置图表生成的默认时间 (默认为60). 推荐设置在 60 到 600 (既 1 到 10 分钟). 如果降低这个参数, stored \*.rrd files should be deleted for the parameter to be taken into account.

    参数**warning-threshold-millis** 和 **severe-threshold-millis** 是一个阀值单位为毫秒( 默认为全局平均值+1个标准差和全局平均值+2x标准差，这个默认值设置为一个动态的阀值可以表现出系统内哪些请求的平均时间不正常). 超过这个阀值，它的平均值会显示为黄色或者红色并分别在汇总表里记录他们的平均次数百分比、点击量等等. 这些阈值参数可以作为一个SLA（ service-level agreement ）的基础，对此可以约束为如“少于2秒的反应时间比为90％的HTTP请求”。

    参数**monitoring-path** (默认为/monitoring ) 用来定义访问监控报表URL如用http://.../admin/performance代替 http://.../monitoring

    参数**no-database** 用来禁用 jdbc connections统计, 设置为true禁用所有。

    参数**disabled** (默认为false ) 用来在需要暂时禁用monitoring或者某些服务器的时候，只需修改tomcat context或者system properties而不用修改web.xml配置的过滤器。

**JDBC**  
        如果你的数据源命名为"jdbc/MyDataSource", 并且配置在应用服务器 (webapp的context),  那么你的sql请求会被自动监控而不需要任何参数(在 Tomcat 5.5 and 6, glassfish 3, jboss 5, weblogic 11g, jetty 6上测试通过).  
        如果你的JDBC驱动是无数据源直接使用的, 那你的驱动类应该定义为："net.bull.javamelody.JdbcDriver" ，然后应该加入jdbc属性"driver"值为真正的dirver class. 例如, 如果你使用的是hibernate.cfg.xml和mysql (无hibernate.connection.datasource):

```
<property name ="hibernate.connection.driver_class" >net.bull.javamelody.JdbcDriver </property>
    <property name ="hibernate.connection.driver">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/myschema
</property>
<property nam="hibernate.connection.username">myuser</property>
    <property name="hibernate.connection.password">mypassword</property>
```

 

        如果你使用了数据源但是名称并不像"jdbc/MyDataSource"这样，或者数据源没有在一个平常的"java:comp/env/" 或者 "java:/"的JNDI 上下文中，那么你可以可以增加可选参数“datasources”  (在system property或filter的上下文中) 去定义应用使用的数据源的JNDI. 如果有多个数据源，这个参数的值可以用逗号分隔。 如果使用 的服务器是jonas V5，数据源可以被监控，但现在看来，它们必须定义在 datasources参数中。  
       例如:

```
  -Djavamelody.datasources=java:comp/env/myapp/MyDataSource 
```

 

        如果数据源定义在spring中, 如：

```
<bean class="org.apache.commons.dbcp.BasicDataSource">...</bean> 
```

         或者

 

```
<bean class="org.springframework.jndi.JndiObjectFactoryBean">...</bean>
```

          那么它也是可以被监控到的，利用Spring post-processor. 须确保Spring的配置文件 (net/bull/javamelody/monitoring-spring.xml ,包含在jar包中)被当作配置文件第一个加载.

        例如：如果你在你的 web.xml中 配置了

```
org.springframework.web.context.ContextLoaderListener
```

          那你的配置中应该配置参数：

```
<context-param>
            <param-name>contextConfigLocation </param-name>
<param-value>
classpath:net/bull/javamelody/monitoring-spring.xml
                    classpath:context/services.xml
                    classpath:context/data-access-layer.xml
                    /WEB-INF/applicationContext.xml
</param-value>
</context-param>
```