All Products
Search
Document Center

Simple Log Service:Get started with Simple Log Service SDK for .NET Core

Last Updated:Oct 26, 2023

This topic describes how to get started with Simple Log Service SDK for .NET Core and perform common operations. For example, you can create a project, create a Logstore, write logs, and query logs.

Prerequisites

  • A Resource Access Management (RAM) user is created, and the required permissions are granted to the RAM user. For more information, see Create a RAM user and grant permissions to the RAM user.

  • The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured. For more information, see Configure environment variables.

    Important
    • The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use the AccessKey pair of a RAM user to call API operations or perform routine O&M.

    • We recommend that you do not save the AccessKey ID or AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and the security of all resources within your account may be compromised.

  • Simple Log Service SDK for .NET Core is installed. For more information, see Install Simple Log Service SDK for .NET Core.

Sample code

In this example, a file named SLSQuickStart.cs is created. The sample code in this file provides an example on how to call API operations to create a project, create a Logstore, create indexes, write logs, and query logs. Example:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Aliyun.Api.LogService;
using Aliyun.Api.LogService.Domain.Log;
using Aliyun.Api.LogService.Domain.LogStore.Index;
using Aliyun.Api.LogService.Infrastructure.Protocol;

namespace Test
{
    class SLSQuickStart
    {
        // The Simple Log Service endpoint. In this example, the Simple Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint. 
        private static string endpoint = "cn-hangzhou.log.aliyuncs.com";
        // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
        private static string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
        private static string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // The name of the project. 
        private static string project = "aliyun-test-project";
        // The name of the Logstore. 
        private static string logstore = "aliyun-test-logstore";
        // Create a Simple Log Service client. 
        private static ILogServiceClient client = BuildSimpleClient();

        static async Task Main(string[] args)
        {
            // Create a project. 
            var proRes = await client.CreateProjectAsync(project, "des");
            check(proRes);
            Console.WriteLine("Create project success");
            Thread.Sleep(120 * 1000);
            
            // Create a Logstore. 
            var storeRes = await client.CreateLogStoreAsync(logstore, 3, 2);
            check(storeRes);
            Console.WriteLine("Create logstore success");
            Thread.Sleep(10 * 1000);
            
            // Create indexes for the Logstore. 
            var indRes = await client.CreateIndexAsync(logstore, new IndexLineInfo(new[] {' ', ','}));
            check(indRes);
            Console.WriteLine("Create Index success");
            Thread.Sleep(60 * 1000);

            // Write data to the Logstore. 
            await PostLogs();
            Console.WriteLine("Post logs success");
            Thread.Sleep(3000);
            // Query logs. 
            await GetLogs();
        }

        public static async Task GetLogs()
        {
            var logsRes = await client.GetLogsAsync(logstore, DateTimeOffset.UtcNow.AddMinutes(-1),
                DateTimeOffset.UtcNow,
                "test", "", 100, 0);
            check(logsRes);
            foreach (var log in logsRes.Result.Logs)
            {
                foreach (var key in log.Keys)
                {
                    log.TryGetValue(key, out var value);
                    Console.WriteLine(key + " : " + value);
                }

                Console.WriteLine("======");
            }
        }

        public static async Task PostLogs()
        {
            for (int i = 0; i < 10; i++)
            {
                var response = await client.PostLogStoreLogsAsync(logstore, new LogGroupInfo
                {
                    Topic = "test",
                    Source = "49.111.66.122",
                    LogTags = new Dictionary<String, String>
                    {
                        {"Tag1", "t1"},
                        {"Tag2", String.Empty},
                        {"Tag3", "t3"}
                    },
                    Logs = new List<LogInfo>
                    {
                        new LogInfo
                        {
                            Time = DateTimeOffset.Now,
                            Contents = new Dictionary<String, String>
                            {
                                {"name", "zs"},
                                {"age", "18"},
                                {"address", String.Empty}
                            }
                        }
                    }
                });
                check(response);
            }
        }

        public static ILogServiceClient BuildSimpleClient()
            => LogServiceClientBuilders.HttpBuilder
                .Endpoint(endpoint, project)
                .Credential(accessKeyId, accessKeySecret)
                .Build();

        public static void check(IResponse res)
        {
            if (!res.IsSuccess)
            {
                throw new ApplicationException(res.Error.ErrorMessage);
            }
        }
    }
}

For more information about sample code, see Alibaba Cloud Simple Log Service SDK for .NET Core.

Response

The following response is returned for the preceding example:

Create project success
Create logstore success
Create Index success
Post logs success
name : zs
age : 18
address :
__topic__ : test
__source__ : 203.0.XX.XX
__tag__:Tag1 : t1
__tag__:Tag2 :
__tag__:Tag3 : t3
__time__ : 1627970965
======
......