package com.lanyuanxiaoyao.service.sync.utils;

import cn.hutool.core.map.MapUtil;
import com.lanyuanxiaoyao.service.common.Constants;
import com.lanyuanxiaoyao.service.common.entity.FlinkJob;
import com.lanyuanxiaoyao.service.common.entity.TableMeta;
import java.io.Serializable;
import java.util.Map;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.MetricGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 指标工具
 *
 * @author ZhangJiacheng
 * @date 2022-06-12
 */
public class MetricsUtils implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(MetricsUtils.class);

    public static Counter counter(RuntimeContext context, FlinkJob job, TableMeta meta, String name) {
        return counter(context, job, meta, name, MapUtil.empty());
    }

    public static Counter counter(RuntimeContext context, FlinkJob job, TableMeta meta, String name, Map<String, String> tags) {
        MetricGroup metricGroup = context.getMetricGroup()
                .addGroup(Constants.METRICS_LABEL_FLINK_JOB_ID, job.getId().toString())
                .addGroup(Constants.METRICS_LABEL_FLINK_JOB_NAME, job.getName())
                .addGroup(Constants.METRICS_LABEL_SCHEMA, meta.getSchema())
                .addGroup(Constants.METRICS_LABEL_TABLE, meta.getTable())
                .addGroup(Constants.METRICS_LABEL_ALIAS, meta.getAlias());
        for (Map.Entry<String, String> entry : tags.entrySet()) {
            metricGroup.addGroup(entry.getKey(), entry.getValue());
        }
        return metricGroup.counter(name);
    }
}
