【转】 使用Python-Diamond收集监控数据

http://blog.csdn.net/iov_aaron/article/details/47299623

Diamond是使用Python实现的用于收集监控数据的工具,主要收集metrics类型的数据,即数据格式一般是metric timestamp value

简单来说, Diamond就是Python实现的守护进程,自动定时的从你的服务或是其它指定数据源中提取数值,并发送到指定的后端(handler) 
Diamond支持多种后端handler, 可以将数据发送到graphite,opentsdb,MySQL,logfile等,并且可以很容易的定制handler

【安装】 
git chone https://github.com/python-diamond/Diamond.git 
cd Diamond 
python setup.py install

【启动】 
python ./bin/diamond –configfile=conf/diamond.conf

【配置】 
[server] 
handlers = diamond.handler.tsdb.TSDBHandler, diamond.handler.archive.ArchiveHandler 
– 具体使用的handler,用来发布/存储metrics, 可以配置多个

handlers_path = /usr/share/diamond/handlers/ 
– handler的路径,如果需要新增handler,则将具体的py实现文件放到该目录,

collectors_path = /usr/share/diamond/collectors/ 
– collector的路径

[handler] 
–该section下配置详细的handler信息,比如使用mysql存储数据 
[[MySQLHandler]] 
hostname = 127.0.0.1 
port = 3306 
username = root 
password = 
database = diamond 
table = metrics 
col_time = timestamp 
col_metric = metric 
col_value = value

[collectors] 
–该session下配置具体的collector信息 
[[DemoCollector]] 
enabled = True – True表示启动该collector 
interval = 60 – metrics数据收集的间隔时间

【定制】 
扩展handler 
handler对应的py实现脚本在handlers_path目录下 
扩展一个handler: 
需要继承Handler类,主要实现process方法 
def process(self, metric)

扩展collector 
collector对应的py实现脚本在collector_path目录下 
扩展一个collector 
需要继承diamond.collector.Collector类,实现collect方法 
def collect(self)

【实例】 
使用mysql进行存储时,发现如果表不存在不会自动创建,而是返回写数据失败; 对其进行修改,加载handler时,如果表不存在则创建。

  1. 添加配置,用于指定数据表的字段类型 
    col_time_type = INT UNSIGNED 
    col_metric_type = VARCHAR(255) 
    col_value_type = VARCHAR(255)

  2. 修改handler实现类: src/diamond/handler/mysql.py

   def __init__(self, config=None)
        ...
        self.col_time_type = self.config['col_time_type']
        self.col_metric_type = self.config['col_metric_type']
        self.col_value_type = self.config['col_value_type']

        # Connect
        self._connect()
        self._prepare()

    def _prepare(self):
        """
        Create Table if not exist
        """
        createSQL = "CREATE TABLE IF NOT EXISTS %s (%s %s, %s %s, %s %s)" % (self.table, self.col_metric, self.col_metric_type, self.col_time, self.col_time_type, self.col_value, self.col_value_type)
        try:
            cursor = self.conn.cursor()
            cursor.execute(createSQL)
            cursor.close()
            self.conn.commit()
        except BaseException, e:
            self.log.error("MySQLHandler: Failed to create data. %s.", e)
            sys.exit(1)
原文地址:https://www.cnblogs.com/zk47/p/6625712.html