通過Gin框架對(duì)接阿里云SLS日志服務(wù),查詢服務(wù)日志,你學(xué)會(huì)了嗎?
阿里云SLS
日志服務(wù) Simple Log Service 是服務(wù)于阿里云客戶以及阿里云集團(tuán)內(nèi)部自用的云原生觀測(cè)與分析,一站式可觀測(cè)數(shù)據(jù)的 Data to Insight 平臺(tái),為 Log、Metric、Trace 等數(shù)據(jù)提供大規(guī)模、低成本、實(shí)時(shí)的平臺(tái)化服務(wù)。日志服務(wù)一站式提供數(shù)據(jù)采集、加工、查詢與分析、可視化、告警、消費(fèi)與投遞等功能,全面提升研發(fā)、運(yùn)維、運(yùn)營(yíng)、安全等場(chǎng)景的數(shù)字化能力。
項(xiàng)目代碼
package main
import (
"fmt"
"github.com/aliyun/aliyun-log-go-sdk"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func main() {
router := gin.Default()
router.GET("/download-logs", func(c *gin.Context) {
// 地區(qū)
endpoint := "cn-beijing.log.aliyuncs.com"
// key
accessKeyID := "LTAI5tShzYy1VMGR17H"
// 密鑰
accessKeySecret := "QELEeTCudJHYhYY3mpuD"
provider := sls.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, "")
client := sls.CreateNormalInterfaceV2(endpoint, provider)
ProjectName := "dean"
LogStoreName := "nginx"
logstore, err := client.GetLogStore(ProjectName, LogStoreName)
if err != nil {
fmt.Println("出現(xiàn)報(bào)錯(cuò)了")
panic(err)
}
fmt.Println("get logstore successfully:", logstore.Name)
// 設(shè)置查詢的時(shí)間范圍
fromTime := time.Now().Unix() - (60 * 60 * 24) // 24小時(shí)之前
toTime := time.Now().Unix() // 當(dāng)前時(shí)間
// 設(shè)置查詢的參數(shù)
query := "*"
line := int64(100) // 每頁(yè)日志條數(shù)
offset := int64(0) // 偏移量
// 獲取日志
resp, err := logstore.GetLogs("", fromTime, toTime, query, line, offset, false)
if err != nil {
fmt.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get logs"})
return
}
logs := resp.Logs
// 將所有日志轉(zhuǎn)換為JSON格式返回
c.JSON(http.StatusOK, logs)
//// 設(shè)置文件名(可以根據(jù)需要自定義)
//filename := "access_log_" + time.Now().Format("20060102150405") + ".txt"
//
//// 設(shè)置HTTP頭信息,指示這是一個(gè)文件下載響應(yīng)
//c.Header("Content-Disposition", "attachment; filename=\""+filename+"\"")
//c.Header("Content-Type", "text/plain")
//
//// 寫入文件內(nèi)容
//c.String(http.StatusOK, logs)
// 設(shè)置下載相關(guān)的頭部信息
c.Header("Content-Description", "File Transfer")
c.Header("Content-Disposition", "attachment; filename=logs.txt")
c.Header("Content-Type", "application/octet-stream")
// 將日志內(nèi)容寫入響應(yīng)體
for _, log := range resp.Logs {
c.Writer.Write([]byte(fmt.Sprintf("%v\n", log)))
}
})
router.Run(":8080")
}
啟動(dòng)代碼程序:
圖片
訪問Nginx服務(wù),然后查看阿里云SLS日志服務(wù):
圖片
訪問接口:
http://127.0.0.1:8080/download-logs
可以看到接口返回內(nèi)容是Nginx的服務(wù)日志,其他功能自行探索。
圖片