适用业务场景:
浏览记录
优点:获取日志使用sdk简单
缺点:浏览会重复
方式:上报日志前端使用Web Tracking采集日志,后端调用aliyun-log的sdk查询日志:
参考:https://help.aliyun.com/document_detail/31752.html?spm=a2c4g.11186623.2.42.75bc67e2O8rC0a#t13028.html
注:阿里云如何配置在官方文档就可以找到
这里只贴后端参考代码:
注: 查询之前需要在阿里云控制台配置索引:单击页面右上角的开启索引。配置索引。
如果配置的索引为:current_user_id则如下:
SlsResultDTO
@Data
public class SlsResultDTO implements Serializable {
private static final long serialVersionUID = 1823552447689642275L;
private List slsResults;
private Integer count;
private String userId;
}
SlsLogsService
@Slf4j
@Service
public class SlsLogsService {
@Resource
SlsConfig slsConfig;
public ObjectResultResponse<SlsResultDTO> getLogs(String userId, SlsVo slsVo){
ObjectResultResponse<SlsResultDTO> response = new ObjectResultResponse<>();
SlsResultDTO slsResultDTO = new SlsResultDTO();
ArrayList slsResults = new ArrayList();
Client client = new Client(slsConfig.getHost(),slsConfig.getAccessKeyId(), slsConfig.getAccessKeySecret());
String topic = "";
Integer from = slsVo.getFrom();
Integer to = slsVo.getTo();
Integer logOffset = 0;
Integer logLine = 10;
if(BeanUtil.isEmpty(from)){
// 1970-01-17 15:32:09
from = 1409529600;
}
if(BeanUtil.isEmpty(to)){
// 当前时间
to = (int) (System.currentTimeMillis() / 1000);
}
if(BeanUtil.isNotEmpty(slsVo.getLogLine())){
logLine = slsVo.getLogLine();
}
if(BeanUtil.isNotEmpty(slsVo.getLogOffset()) && !CommonConstant.IS_DOWN.equals(slsVo.getLogOffset())){
logOffset = (slsVo.getLogOffset() - 1) * logLine;
}
String query = "current_user_id: " + userId;
GetLogsRequest req = new GetLogsRequest(slsConfig.getProject(), slsVo.getLogStore(),
from, to, topic, query, logOffset, logLine, true);
GetLogsResponse res = null;
try {
res = client.GetLogs(req);
ArrayList<QueriedLog> logs = res.GetLogs();
slsResultDTO.setCount(res.GetCount());
for (QueriedLog logA:logs) {
slsResults.add(logA.GetLogItem().ToJsonString());
}
log.info("获取用户足迹记录请求:{}", GsonUtils.toJsonWtihNullField(req));
} catch (LogException e) {
log.error("获取用户足迹异常:{}",e.GetErrorMessage());
response.setStatus(HttpStatusConstant.FAIL);
response.setMessage("查询用户足迹异常");
return response;
}
slsResultDTO.setUserId(userId);
slsResultDTO.setSlsResults(slsResults);
response.setData(slsResultDTO);
log.info("获取用户足迹记录结果:{}", JSONObject.toJSONString(res));
return response;
}
配置文件:
@Component
@Data
public class SlsConfig {
/**
* 账号AccessKey信息
*/
@Value("${sls.accessKeyId}")
private String accessKeyId;
/**
* 账号AccessKey信息
*/
@Value("${sls.accessKeySecret}")
private String accessKeySecret;
@Value("${sls.host}")
private String host;
@Value("${sls.project}")
private String project;
}
其中
query的语法可以参考:https://help.aliyun.com/document_detail/29060.html?spm=a2c4g.11186623.6.820.5ae3562dyH1ANa
topic :根据情况设置log或者空
参数解释:
参考:getLogs
注:转载注明出处:https://blog.csdn.net/weixin_41546244