Skip to content

Instantly share code, notes, and snippets.

@ajtatum
Created February 24, 2020 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajtatum/6a5358f760a312ac490119028ca41dd7 to your computer and use it in GitHub Desktop.
Save ajtatum/6a5358f760a312ac490119028ca41dd7 to your computer and use it in GitHub Desktop.
Serilog Configuration
public class Program
{
public static async Task Main(string[] args)
{
await CreateHostBuilder(args).Build().RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddJsonFile("appsettings.json", false, true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true, true);
configApp.AddEnvironmentVariables();
configApp.AddCommandLine(args);
})
.UseSerilog((hostingContext, loggerConfiguration) =>
{
var columnOptions = new ColumnOptions
{
ClusteredColumnstoreIndex = false,
DisableTriggers = true,
AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn("Application", SqlDbType.VarChar, true, 50) {NonClusteredIndex = true},
new SqlColumn("Environment", SqlDbType.VarChar, true, 50),
new SqlColumn("BuildNumber", SqlDbType.VarChar, true, 50),
new SqlColumn("RequestPath", SqlDbType.VarChar, true, 255)
}
};
columnOptions.Store.Add(StandardColumn.LogEvent);
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.PrimaryKey = columnOptions.Id;
columnOptions.Id.NonClusteredIndex = true;
columnOptions.Level.ColumnName = "Severity";
columnOptions.Level.DataLength = 15;
var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.InstrumentationKey = hostingContext.Configuration["ApplicationInsights:InstrumentationKey"];
loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.Enrich.WithProperty("Application", hostingContext.Configuration["ApplicationName"])
.Enrich.WithProperty("Environment", hostingContext.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("BuildNumber", hostingContext.Configuration["BuildNumber"])
.WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Traces)
.WriteTo.MSSqlServer(hostingContext.Configuration.GetConnectionString("LogsConnection"), tableName: "Logs", columnOptions: columnOptions, autoCreateSqlTable: true, batchPostingLimit: 50, period: new TimeSpan(0, 0, 5))
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss.fff} {ThreadId} {EventType:x8} {Level:u3}] {Message:lj}{NewLine}{Exception}", theme: AnsiConsoleTheme.Code);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment