DEV Community

Cover image for Custom properties in Elastic Search using C# and Serilog
Rafael Firmino
Rafael Firmino

Posted on

Custom properties in Elastic Search using C# and Serilog

Hi dears!

Today I show you how create a Custom properties for elasticsearch using c# and Serilog.

I Have serilog configuration for send logs to elasticsearch

public class SerilogConfiguration{

    public static void GetFileAndElasticSearchLogger(IConfigurationRoot configuration = null)
      {
          var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
          configuration ??= new ConfigurationBuilder()
              .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
              .AddJsonFile(
                  $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
                  optional: true)
              .AddEnvironmentVariables()
              .Build();

          Log.Logger = new LoggerConfiguration()
              .Enrich.FromLogContext()
              .WriteTo.Debug()
              .WriteTo.Console(
                outputTemplate: "Level:{Level:u4} Tenant:{TenantId} Time:{Timestamp:HH:mm:ss} Message:{Message:lj}{NewLine}{Exception}"
              )
              .WriteTo.Elasticsearch(ConfigureElasticSink(configuration["App:Id"], configuration, environment))
              .Enrich.WithProperty("Environment", environment)
              .ReadFrom.Configuration(configuration)
              .CreateLogger();
      }

      private static ElasticsearchSinkOptions ConfigureElasticSink(string applicationName, IConfigurationRoot configuration, string environment)
      {
          var env = environment?.ToLower().Replace(".", "-");
          if (configuration["ElasticSearch:Password"] != null)
          {
              return new ElasticsearchSinkOptions(new Uri(configuration["ElasticSearch:Uri"]))
              {

                  ModifyConnectionSettings = x => x.BasicAuthentication(
                      configuration["ElasticSearch:User"],
                      configuration["ElasticSearch:Password"]
                  ) ,
                  AutoRegisterTemplate = true,
                  IndexFormat = $"DEV-TO-EXAMPLE-{applicationName}{(env != null? "-"+env : "")}"
              };
          }
          return new ElasticsearchSinkOptions(new Uri(configuration["ElasticSearch:Uri"]))
          {
              AutoRegisterTemplate = true,
              IndexFormat = $"DEV-TO-EXAMPLE-{applicationName}{(env != null? "-"+env : "")}"
          };

      }
    }

Enter fullscreen mode Exit fullscreen mode

Now we need load configuration in startup.cs

public static int Main(string[] args){        { 
SerilogConfiguration.GetFileAndElasticSearchLogger();
...
}
Enter fullscreen mode Exit fullscreen mode

Now we need call a logger methods

var Logger = Serilog.Log.Logger;
Logger
.ForContext("LogName", "Dev.To Example")
.ForContext(ExecutionTime, 1500)
.Information("Created Log....")
Enter fullscreen mode Exit fullscreen mode

Wen this method register the log in elasticsearch the elastic search attach these properties in "fields"

Now we can search log using de KQL

fields.LogName: "%.TO%"
//or 
fields.ExecutionTime > 1500
Enter fullscreen mode Exit fullscreen mode

Discussion (0)