亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

.net core 使用阿里云分布式日志的配置方法

 更新時(shí)間:2021年06月08日 08:31:13   作者:提伯斯  
本文給大家分享.net core 使用阿里云分布式日志的實(shí)現(xiàn)代碼,簡單查詢阿里云日志的工具使用,通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

前言

好久沒有出來夸白了,今天教大家簡單的使用阿里云分布式日志,來存儲(chǔ)日志,沒有阿里云賬號(hào)的,可以免費(fèi)注冊一個(gè)

開通阿里云分布式日志(有一定的免費(fèi)額度,個(gè)人測試學(xué)習(xí)完全沒問題的,香)

阿里云日志地址:https://sls.console.aliyun.com/lognext/profile

先開通阿里云日志,這個(gè)比較簡單授權(quán)就可以了

選擇接入數(shù)據(jù),我們這里選 .NET

選擇項(xiàng)目名稱,沒有項(xiàng)目的可以去創(chuàng)建一個(gè),項(xiàng)目名稱后面會(huì)用到,如果你有購買阿里云ECS,項(xiàng)目區(qū)域最好選擇跟ECS同一個(gè)區(qū)域(每個(gè)區(qū)域的地址不一樣,同一個(gè)區(qū)域可以選擇內(nèi)網(wǎng)通訊,速度更快),如果沒有,就隨便選個(gè)區(qū)域,我這里選擇的是杭州

選擇日志庫,沒有就創(chuàng)建一個(gè)

數(shù)據(jù)源配置,這個(gè)先不用管,后面有教程

設(shè)置分析配置,例如我這里設(shè)置了兩個(gè),可以根據(jù)業(yè)務(wù)需求來,沒有特殊要求不用設(shè)置

開通完成,可以正??吹絻x盤表

設(shè)置密鑰

通過SDK 寫入日志

阿里云有提供對應(yīng)的SDK(阿里云 .NET SDK的質(zhì)量大家都懂),它主要是通過構(gòu)造一個(gè)靜態(tài)對象來提供訪問的,地址: https://github.com/aliyun/aliyun-log-dotnetcore-sdk

阿里云代碼

LogServiceClientBuilders.HttpBuilder
    .Endpoint("<endpoint>", "<projectName>")
    .Credential("<accessKeyId>", "<accessKey>")
    .Build();

阿里云提供的依賴注入代碼(autofac),很遺憾按照這個(gè)方式,并沒有獲取到對象

using Aliyun.Api.LogService;
using Autofac;

namespace Examples.DependencyInjection
{
    public static class AutofacExample
    {
        public static void Register(ContainerBuilder containerBuilder)
        {
            containerBuilder
                .Register(context => LogServiceClientBuilders.HttpBuilder
                    // 服務(wù)入口<endpoint>及項(xiàng)目名<projectName>
                    .Endpoint("<endpoint>", "<projectName>")
                    // 訪問密鑰信息
                    .Credential("<accessKeyId>", "<accessKey>")
                    .Build())
                // `ILogServiceClient`所有成員是線程安全的,建議使用Singleton模式。
                .SingleInstance();
        }
    }
}

中間個(gè)有小插曲,由于公司使用阿里云日志比較早,也非常穩(wěn)定,替換成我申請的阿里云日志的配置,發(fā)送日志一直報(bào)錯(cuò),找了半天沒找到原因,提了工單,原來阿里云使用了新的SDK


重新封裝阿里云日志SDK(Aliyun.Log.Core) https://github.com/wmowm/Aliyun.Log.Core問了下群友,剛好有大佬重寫過向阿里云提交日志這塊,一番py交易,代碼塊到手,主要是數(shù)據(jù)組裝,加密,發(fā)送,發(fā)送部分的代碼基于http的protobuf服務(wù)實(shí)現(xiàn),這里直接從阿里云開源的SDK里拷貝過來,開始重新封裝,主要實(shí)現(xiàn)以下功能

  • 實(shí)現(xiàn).net core DI
  • 加入隊(duì)列,讓日志先入列,再提交到阿里云,提高系統(tǒng)吞吐量
  • 對日志模型進(jìn)行封裝,滿足基礎(chǔ)業(yè)務(wù)需求

代碼如下

添加ServiceCollection 拓展,定義一個(gè)阿里云日志的配置信息委托,然后將需要注入的服務(wù)注冊進(jìn)去即可

 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);
  }

加入隊(duì)列比較簡單,定義一個(gè)隊(duì)列,使用HostedService 消費(fèi)隊(duì)列

 /// <summary>
  /// 寫日志
  /// </summary>
  /// <param name="log"></param>
  /// <returns></returns>
  public async Task Log(LogModel log)
  {
      AliyunLogBuilder.logQueue.Enqueue(log);
  }
/// <summary>
  /// 消費(fèi)隊(duì)列
  /// </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);
              }
          }
      }
  });

定義日志模型,可以根據(jù)業(yè)務(wù)情況拓展

public class LogModel
  {
      /// <summary>
      /// 所在類
      /// </summary>
      public string ClassName { get; set; }


      /// <summary>
      /// 訂單號(hào)
      /// </summary>
      public string OrderNo { get; set; }


      /// <summary>
      /// 提交時(shí)間
      /// </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");
}

簡單的查詢?nèi)罩?/h2>

同事寫了一個(gè)查詢阿里云日志的工具,非常實(shí)用,我用 .net core又抄了一遍,一并開源在github,地址: https://github.com/wmowm/Aliyun.Log.Core/tree/main/Aliyun.Log.Core.Client

推薦我自己寫的一個(gè)Redis消息隊(duì)列中間件InitQ,操作簡單可以下載的玩玩
https://github.com/wmowm/initq

到此這篇關(guān)于.net core 使用阿里云分布式日志的文章就介紹到這了,更多相關(guān).net core分布式日志內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論