Skip to content

Commit

Permalink
feat: add option to enable elasticsearch formatter for console logs
Browse files Browse the repository at this point in the history
  • Loading branch information
abhith committed Jul 18, 2020
1 parent cb92625 commit 8957576
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
3 changes: 2 additions & 1 deletion Samples/AspNetCoreApp/appsettings.json
Expand Up @@ -11,6 +11,7 @@
}
},
"SeqServerUrl": "http://localhost:5341/",
"WriteToFile": true
"WriteToFile": true,
"UseElasticsearchFormatter": false
}
}
4 changes: 4 additions & 0 deletions docs/articles/aspnet-core/logging.md
Expand Up @@ -117,6 +117,10 @@ If `SeqServerUrl` is provided (ex. "http://localhost:5341/"), then seq sink gets

To enable logging to file, set it to `true`. Default value is `false`.

### UseElasticsearchFormatter

Set this to `true` if you want your console logs to written in elasticsearch format, useful in case of hosting in k8s where EFK configured to collect logs. Default value is `false`.

We don't need the default **Logging** configuration in the **appsettings.json** anymore, remove it.

```json
Expand Down
1 change: 1 addition & 0 deletions src/Code.Library.AspNetCore/Code.Library.AspNetCore.csproj
Expand Up @@ -26,6 +26,7 @@ Specific to ASP.NET Core project.</Description>
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
<PackageReference Include="Serilog.Exceptions" Version="5.6.0+build.406" />
<PackageReference Include="Serilog.Formatting.Compact" Version="1.1.0" />
<PackageReference Include="Serilog.Formatting.Elasticsearch" Version="8.2.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
Expand Down
12 changes: 10 additions & 2 deletions src/Code.Library.AspNetCore/Helpers/SerilogHelper.cs
Expand Up @@ -9,6 +9,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Serilog.Formatting.Elasticsearch;

namespace Code.Library.AspNetCore.Helpers
{
Expand Down Expand Up @@ -98,11 +99,18 @@ public static class SerilogHelper
.Enrich.WithProperty("Assembly", $"{name.Name}")
.Enrich.WithProperty("Version", $"{name.Version}")
.Destructure.UsingAttributes()
.WriteTo.Console()

// TODO(abhith): find alternative for TelemetryConfiguration.Active
.WriteTo.ApplicationInsights(TelemetryConfiguration.Active, TelemetryConverter.Traces);

if (configuration.GetValue<bool>("Serilog:UseElasticsearchFormatter", false))
{
loggerConfig.WriteTo.Console(new ElasticsearchJsonFormatter());
}
else
{
loggerConfig.WriteTo.Console();
}

if (configuration.GetValue<bool>("Serilog:WriteToFile", false))
{
loggerConfig.WriteTo.File(new RenderedCompactJsonFormatter(),
Expand Down

0 comments on commit 8957576

Please sign in to comment.