一、增加config.go 
? ? ? ? ? 在上文中创建的module中,在flow目录中增加config.go,代码示例:  
package flow
type config struct {
        NETCARD string `config:"flow.NETCARD"`
}
func defaultConfig() config {
        return config{
                // 设置默认值,如果在配置文件中不配置该字段值,该字段默认值为ens33
                NETCARD: "ens33",
        }
}
  
二、完善flow.go文件 
// 在metricset结构体中增加config字段
type MetricSet struct {
        mb.BaseMetricSet
        // 增加config
        config     config
        counter int
}
// 在new函数中读取配置文件
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
        cfgwarn.Beta("The domain flow metricset is beta.")
        //config := struct{}{}
        // 读取配置文件
        config := defaultConfig()
        if err := base.Module().UnpackConfig(&config); err != nil {
                return nil, err
        }
        return &MetricSet{
                BaseMetricSet: base,
                config:        config,
                counter:       1,
        }, nil
}
// 在fetch函数中引用NETWORK字段
func (m *MetricSet) Fetch(report mb.ReporterV2) error {
        report.Event(mb.Event{
                MetricSetFields: common.MapStr{
                        "VALUE":  "test_create_module",
                        // 引用NETWORK字段
                        "NETWORKCARD": m.config.NETCARD,
                        "counter": m.counter,
                },
        })
        m.counter++
        return nil
}
  
三、设置配置文件 
- module: domain
  enabled: true
  period: 10s
  // 设置自定义字段值
  flow.NETCARD: "ens22"
  metricsets:
    - flow
  
四、验证: 
   
根据发出日志可以看到,配置文件中自定义字段值已经读取到并且成功发送,说明自定义字段创建成功。? 
                
        
        
    
  
 
 |