前言
好久沒有出來誇白了,今天教大家簡單的使用阿裡雲分布式日志,來存儲日志,沒有阿裡雲賬号的,可以免費注冊一個![]()
.net core 使用阿裡雲分布式日志
開通阿裡雲分布式日志(有一定的免費額度,個人測試學習完全沒問題的,香)
阿裡雲日志位址:https://sls.console.aliyun.com/lognext/profile
- 先開通阿裡雲日志,這個比較簡單授權就可以了
- 選擇接入資料,我們這裡選 .NET
.net core 使用阿裡雲分布式日志 - 選擇項目名稱,沒有項目的可以去建立一個,項目名稱後面會用到,如果你有購買阿裡雲ECS,項目區域最好選擇跟ECS同一個區域(每個區域的位址不一樣,同一個區域可以選擇内網通訊,速度更快),如果沒有,就随便選個區域,我這裡選擇的是杭州
.net core 使用阿裡雲分布式日志 - 選擇日志庫,沒有就建立一個
.net core 使用阿裡雲分布式日志 - 資料源配置,這個先不用管,後面有教程
- 設定分析配置,例如我這裡設定了兩個,可以根據業務需求來,沒有特殊要求不用設定
.net core 使用阿裡雲分布式日志 - 開通完成,可以正常看到儀盤表
.net core 使用阿裡雲分布式日志 - 設定密鑰
.net core 使用阿裡雲分布式日志
通過SDK 寫入日志
- 阿裡雲有提供對應的SDK(阿裡雲 .NET SDK的品質大家都懂),它主要是通過構造一個靜态對象來提供通路的,位址: https://github.com/aliyun/aliyun-log-dotnetcore-sdk
- 阿裡雲代碼
LogServiceClientBuilders.HttpBuilder
.Endpoint("<endpoint>", "<projectName>")
.Credential("<accessKeyId>", "<accessKey>")
.Build();
- 阿裡雲提供的依賴注入代碼(autofac),很遺憾按照這個方式,并沒有擷取到對象
using Aliyun.Api.LogService;
using Autofac;
namespace Examples.DependencyInjection
{
public static class AutofacExample
{
public static void Register(ContainerBuilder containerBuilder)
{
containerBuilder
.Register(context => LogServiceClientBuilders.HttpBuilder
// 服務入口<endpoint>及項目名<projectName>
.Endpoint("<endpoint>", "<projectName>")
// 通路密鑰資訊
.Credential("<accessKeyId>", "<accessKey>")
.Build())
// `ILogServiceClient`所有成員是線程安全的,建議使用Singleton模式。
.SingleInstance();
}
}
}
- 中間個有小插曲,由于公司使用阿裡雲日志比較早,也非常穩定,替換成我申請的阿裡雲日志的配置,發送日志一直報錯,找了半天沒找到原因,提了工單,原來阿裡雲使用了新的SDK
.net core 使用阿裡雲分布式日志 .net core 使用阿裡雲分布式日志
重新封裝阿裡雲日志SDK(Aliyun.Log.Core) https://github.com/wmowm/Aliyun.Log.Core
- 問了下群友,剛好有大佬重寫過向阿裡雲送出日志這塊,一番py交易,代碼塊到手,主要是資料組裝,加密,發送,發送部分的代碼基于http的protobuf服務實作,這裡直接從阿裡雲開源的SDK裡拷貝過來,開始重新封裝,主要實作以下功能
- 實作 .net core DI
- 加入隊列,讓日志先入列,再送出到阿裡雲,提高系統吞吐量
- 對日志模型進行封裝,滿足基礎業務需求
代碼如下
- 添加ServiceCollection 拓展,定義一個阿裡雲日志的配置資訊委托,然後将需要注入的服務注冊進去即可
public static AliyunLogBuilder AddAliyunLog(this IServiceCollection services, Action<AliyunSLSOptions> setupAction)
{
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
//var options = new AliyunSLSOptions();
//setupAction(options);
services.Configure(setupAction);
services.AddHttpClient();
services.AddSingleton<AliyunSLSClient>();
services.AddSingleton<AliyunLogClient>();
services.AddHostedService<HostedService>();
return new AliyunLogBuilder(services);
}
- 加入隊列比較簡單,定義一個隊列,使用HostedService 消費隊列
/// <summary>
/// 寫日志
/// </summary>
/// <param name="log"></param>
/// <returns></returns>
public async Task Log(LogModel log)
{
AliyunLogBuilder.logQueue.Enqueue(log);
}
/// <summary>
/// 消費隊列
/// </summary>
Task.Run(async () =>
{
using (var serviceScope = _provider.GetService<IServiceScopeFactory>().CreateScope())
{
var _options = serviceScope.ServiceProvider.GetRequiredService<IOptions<AliyunSLSOptions>>();
var _client = serviceScope.ServiceProvider.GetRequiredService<AliyunSLSClient>();
while (true)
{
try
{
if (AliyunLogBuilder.logQueue.Count>0)
{
var log = AliyunLogBuilder.logQueue.Dequeue();
var logInfo = new LogInfo
{
Contents =
{
{"Topic", log.Topic.ToString()},
{"OrderNo", log.OrderNo},
{"ClassName", log.ClassName},
{ "Desc",log.Desc},
{ "Html",log.Html},
{ "PostDate",log.PostDate},
},
Time = DateTime.Parse(log.PostDate)
};
List<LogInfo> list = new List<LogInfo>() { logInfo };
var logGroupInfo = new LogGroupInfo
{
Topic = log.Topic.ToString(),
Source = "localhost",
Logs = list
};
await _client.PostLogs(new PostLogsRequest(_options.Value.LogStoreName, logGroupInfo));
}
else
{
await Task.Delay(1000);
}
}
catch (Exception ex)
{
await Task.Delay(1000);
}
}
}
});
- 定義日志模型,可以根據業務情況拓展
public class LogModel
{
/// <summary>
/// 所在類
/// </summary>
public string ClassName { get; set; }
/// <summary>
/// 訂單号
/// </summary>
public string OrderNo { get; set; }
/// <summary>
/// 送出時間
/// </summary>
public string PostDate { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Desc { get; set; }
/// <summary>
/// 長字段描述
/// </summary>
public string Html { get; set; }
/// <summary>
/// 日志主題
/// </summary>
public string Topic { get; set; } = "3";
}
使用Aliyun.Log.Core
- 擷取Aliyun.Log.Core包
方案A. install-package Aliyun.Log.Core
方案B. nuget包管理工具搜尋 Aliyun.Log.Core
- 添加中間件
services.AddAliyunLog(m =>
{
m.AccessKey = sls.GetValue<string>("AccessKey");
m.AccessKeyId = sls.GetValue<string>("AccessKeyId");
m.Endpoint = sls.GetValue<string>("Host");
m.Project = sls.GetValue<string>("Project");
m.LogStoreName = sls.GetValue<string>("LogstoreName");
});
- 寫入日志
//擷取對象
private readonly IOptions<SlsOptions> _options;
private readonly AliyunLogClient _aliyunLogClient;
public HomeController(IOptions<SlsOptions> options, AliyunLogClient aliyunLogClient)
{
_options = options;
_aliyunLogClient = aliyunLogClient;
}
[HttpGet("/api/sendlog")]
public async Task<JsonResult> SendLog(string topic="1")
{
//日志模型
LogModel logModel = new LogModel()
{
ClassName = "Aliyun.log",
Desc = "6666666666xxxxxx",
Html = "99999999999xxxxx",
Topic = topic,
OrderNo = Guid.NewGuid().ToString("N"),
PostDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
};
await _aliyunLogClient.Log(logModel);
return Json("0");
}
簡單的查詢日志
- 同僚寫了一個查詢阿裡雲日志的工具,非常實用,我用 .net core又抄了一遍,一并開源在github,位址: https://github.com/wmowm/Aliyun.Log.Core/tree/main/Aliyun.Log.Core.Client
-
推薦我自己寫的一個Redis消息隊列中間件InitQ,操作簡單可以下載下傳的玩玩
https://github.com/wmowm/initq