DEV Community

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

Posted on

3

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more