.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("", “”)
// 访问密钥信息
.Credential("", “”)
.Build())
// ILogServiceClient所有成员是线程安全的,建议使用Singleton模式。
.SingleInstance();
}
}
}
中间个有小插曲,由于公司使用阿里云日志比较早,也非常稳定,替换成我申请的阿里云日志的配置,发送日志一直报错,找了半天没找到原因,提了工单,原来阿里云使用了新的SDK
blockchain
blockchain
blockchain

重新封装阿里云日志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 setupAction)
{
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
//var options = new AliyunSLSOptions();
//setupAction(options);
services.Configure(setupAction);
services.AddHttpClient();
services.AddSingleton();
services.AddSingleton();
services.AddHostedService();

  return new AliyunLogBuilder(services);

}
加入队列比较简单,定义一个队列,使用HostedService 消费队列
///
/// 写日志
///
///
///
public async Task Log(LogModel log)
{
AliyunLogBuilder.logQueue.Enqueue(log);
}
///
/// 消费队列
///
Task.Run(async () =>
{
using (var serviceScope = _provider.GetService().CreateScope())
{
var _options = serviceScope.ServiceProvider.GetRequiredService<IOptions>();
var _client = serviceScope.ServiceProvider.GetRequiredService();
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 list = new List() { 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
{
///
/// 所在类
///
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(“AccessKey”);
m.AccessKeyId = sls.GetValue(“AccessKeyId”);
m.Endpoint = sls.GetValue(“Host”);
m.Project = sls.GetValue(“Project”);
m.LogStoreName = sls.GetValue(“LogstoreName”);
});
写入日志
//获取对象
private readonly IOptions _options;
private readonly AliyunLogClient _aliyunLogClient;
public HomeController(IOptions options, AliyunLogClient aliyunLogClient)
{
_options = options;
_aliyunLogClient = aliyunLogClient;
}

[HttpGet("/api/sendlog")]
public async Task 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”);
}
USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
亚马逊测评 www.yisuping.cn
深圳网站建设www.sz886.com

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值