Last active
April 26, 2021 13:42
-
-
Save pichayean/c14fa756068ccaf893aeed8db9895a7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.Hosting; | |
using Microsoft.Extensions.Logging; | |
using Serilog; | |
using Serilog.Sinks.Elasticsearch; | |
using System.Reflection; | |
namespace Webapi_Serilog | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
ConfigureLogging(); | |
CreateHost(args); | |
} | |
private static void ConfigureLogging() | |
{ | |
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); | |
var configuration = new ConfigurationBuilder() | |
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) | |
.AddJsonFile( | |
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", | |
optional: true) | |
.Build(); | |
Log.Logger = new LoggerConfiguration() | |
.Enrich.FromLogContext() | |
.Enrich.WithMachineName() | |
.WriteTo.Debug() | |
.WriteTo.Console() | |
.WriteTo.Elasticsearch(ConfigureElasticSink(configuration, environment)) | |
.Enrich.WithProperty("Environment", environment) | |
.ReadFrom.Configuration(configuration) | |
.CreateLogger(); | |
} | |
private static ElasticsearchSinkOptions ConfigureElasticSink(IConfigurationRoot configuration, string environment) | |
{ | |
return new ElasticsearchSinkOptions(new Uri(configuration["ElasticConfiguration:Uri"])) | |
{ | |
AutoRegisterTemplate = true, | |
IndexFormat = $"{Assembly.GetExecutingAssembly().GetName().Name.ToLower()}-{environment?.ToLower().Replace(".", "-")}-{DateTime.UtcNow:yyyy-MM}" | |
}; | |
} | |
private static void CreateHost(string[] args) | |
{ | |
try | |
{ | |
CreateHostBuilder(args).Build().Run(); | |
} | |
catch (System.Exception ex) | |
{ | |
Log.Fatal($"Start Failed! {Assembly.GetExecutingAssembly().GetName().Name}", ex); | |
throw; | |
} | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.UseStartup<Startup>(); | |
}) | |
.ConfigureAppConfiguration(configuration => | |
{ | |
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); | |
configuration.AddJsonFile( | |
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", | |
optional: true); | |
}) | |
.UseSerilog(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment