【工具笔记】java 阿里云日志服务SLS查询工具

        <dependency>
            <groupId>com.aliyun.openservices</groupId>
            <artifactId>aliyun-log</artifactId>
            <version>0.6.64</version>
            <classifier>jar-with-dependencies</classifier>
        </dependency>
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.request.PutLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;

public class AliyunLogUtil<T> {
	private static String host = null;
	private static String accessId = null;
	private static String accessKey = null;
	private static Client client = new Client(host, accessId, accessKey);
	private String project = null;
	private String logstore = null;
	private Class<T> clz = null;
	
	public AliyunLogUtil(String project, String logstore, Class<T> clz) {
		this.project = project;
		this.logstore = logstore;
		this.clz = clz;
	}
	
	/**
	 * 
	 * @param topic
	 * @param ttl_in_day:3650表示永久
	 * @param shard_count
	 * @param source
	 * @param params
	 */
	public void savelog(String topic, int ttl_in_day, int shard_count, String source, T bean) {
		 Vector<LogItem> logGroup = new Vector<LogItem>();
		 LogItem logItem = new LogItem((int) (new Date().getTime() / 1000));
		 String json = JSON.toJSONString(bean);
		 JSONObject params = JSON.parseObject(json);
		 for(Entry<String, Object> entry : params.entrySet()) {
			 logItem.PushBack(entry.getKey(), String.valueOf(entry.getValue()));
		 }
		 logGroup.add(logItem);
        
         PutLogsRequest req2 = new PutLogsRequest(project, logstore, topic, source, logGroup);
         try {
			client.PutLogs(req2);
//			System.out.println(">>>>>>>>>>:发送阿里云日志完成");
		} catch (LogException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param from:	查询开始时间点。Unix时间戳格式,表示从1970-1-1 00:00:00 UTC计算起的秒数
	 * @param to:查询结束时间点。Unix时间戳格式,表示从1970-1-1 00:00:00 UTC计算起的秒数
	 * @param topic:日志主题
	 * @param query:日志主题查询和分析语句。更多信息,请参见查询简介和分析简介。
	 * @param line:请求返回的最大日志条数。最小值为0,最大值为100,默认值为100。
	 * @param offset:查询开始行。默认值为0
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public int getCount(int from, int to, String topic, String query, int line, int offset) {
		try {
			GetLogsResponse res4 = null;
			//对于每个Offset,一次读取100行日志,如果读取失败,最多重复读取3次。
            for (int retry_time = 0; retry_time < 3; retry_time++) {
            	GetLogsRequest req4 = new GetLogsRequest(project, logstore, from, to, topic, (query == null ? "" : query) + " | SELECT COUNT(*) as count", offset, line, false);
//    			System.out.println(">>>阿里云日志服务访问参数:" + JSON.toJSONString(req4.GetAllParams()));
                res4 = client.GetLogs(req4);
                if (res4 != null && res4.IsCompleted()) {
                    break;
                }
                Thread.sleep(200);
            }
            if(res4==null) {
            	return 0;
            }
			List<QueriedLog> list = res4.getLogs();
			if(list==null||list.size()==0) {
				return 0;
			}
			QueriedLog log = list.get(0);
//			System.out.println(">>>阿里云日志服务访问结果:"+JSON.toJSONString(log));
			Map resMap = JSON.parseObject(log.GetLogItem().ToJsonString(), Map.class);
			String countStr = String.valueOf(resMap.get("count"));
			return Integer.parseInt(countStr==null?"0":countStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 
	 * @param from:	查询开始时间点。Unix时间戳格式,表示从1970-1-1 00:00:00 UTC计算起的秒数
	 * @param to:查询结束时间点。Unix时间戳格式,表示从1970-1-1 00:00:00 UTC计算起的秒数
	 * @param topic:日志主题
	 * @param query:日志主题查询和分析语句。更多信息,请参见查询简介和分析简介。
	 * @param line:请求返回的最大日志条数。最小值为0,最大值为100,默认值为100。
	 * @param offset:查询开始行。默认值为0
	 * @return
	 */
	public List<T> getLog(int from, int to, String topic, String query, int line, int offset) {
		if(line>100) {
			line = 100;
		}
		try {
			GetLogsResponse res4 = null;
			//对于每个Offset,一次读取100行日志,如果读取失败,最多重复读取3次。
            for (int retry_time = 0; retry_time < 3; retry_time++) {
                GetLogsRequest req4 = new GetLogsRequest(project, logstore, from, to, topic, query, offset, line, true);
//                System.out.println(">>>阿里云日志服务访问参数:"+JSON.toJSONString(req4.GetAllParams()));
                res4 = client.GetLogs(req4);
                if (res4 != null && res4.IsCompleted()) {
                    break;
                }
                Thread.sleep(200);
            }
            if(res4==null) {
            	return null;
            }
//            System.out.println("Read log count:" + String.valueOf(res4.GetCount()));
            List<T> res = new ArrayList<T>();
            List<QueriedLog> list = res4.getLogs();
			for(int i = 0; list!=null&&i<list.size(); i++) {
				QueriedLog log = list.get(i);
				T resTmp = JSON.parseObject(log.GetLogItem().ToJsonString(), clz);
//				System.out.println(log.GetLogItem().ToJsonString());
				res.add(resTmp);
			}
//			System.out.println(">>>阿里云日志服务访问结果:"+JSON.toJSONString(res));
			return res;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孔小胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值