hello,Aliyun SLS

Aliyun SLS

日志服务一站式提供数据采集、加工、查询与分析、可视化、告警、消费与投递等功能,全面提升您在研发、运维、运营、安全等场景的数字化能力。

SLS算得上是阿里云的明星级产品,确实很好用.

场景设定

有一台server,为了监测它自身以及它访问网络的健康状况.

方案: 这台server会运行一个crontab任务,每分钟上报心跳信息给中心服务器.中心服务器则会将心跳信息写入SLS.

1. client上报心跳

1
2
3
4
5
6
7
8
9
#!/bin/bash

hostname=`hostname`
macAddress="mock_mac_addr"
timestampNano=`date '+%s%N'`
username=`whoami`
privateIP=`hostname -I | awk '{print $1}'`

curl --max-time 20 -d "privateIP=$privateIP&macAddress=$macAddress&username=$username&timestampNano=$timestampNano&hostname=$hostname" "https://www.example.com/heartbeat.do"

2. server端写入sls

前提是在SLS已经建好对应的project和logstore

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@RequestMapping("/heartbeat")
public void heartbeat(HttpServletRequest request, HttpServletResponse response) {
WebResult result = new WebResult();
try {
String macAddress = request.getParameter("macAddress");
String username = request.getParameter("username");
String hostname = request.getParameter("hostname");
String timestampNano = request.getParameter("timestampNano");
String privateIP = request.getParameter("privateIP");
String remoteIP = NetworkUtils.getIpAddress(request);
timestampNano = StringUtils.left(timestampNano, 13);
timestampNano = StringUtils.rightPad(timestampNano, 13, '0');
Map<String, String> logData = new HashMap<>();
logData.put("macaddress", macAddress);
logData.put("user", username);
logData.put("hostname", hostname);
logData.put("ip", remoteIP);
logData.put("timestamp", timestampNano);
SLSUtils.asyncSendToSLS("prject_name", "logstore_name", logData);
} catch (Exception e) {
logger.error(e.getMessage(), e);
result.setErrorMsg(e.getMessage());
result.setSuccess(false);
}
outputToJSON(response, result);
}

配置大盘&报警

大盘&报警语句

报警只要看最近的数据,所以可以把limit调小

1
(hostname : "hostname")| select time_series(__time__, '1m', '%H:%i:%s' ,'0') as Time, count(1) as online group by Time order by Time limit 10000 

SLS支持的报警通道很丰富: 钉钉,微信,webhook都是支持,可以按需配置.还有一个功能很好用就是大盘支持”订阅”.这样就能把大盘概览每天推送到钉钉或者其他平台.

image-20220824234130013