All Projects → serilog → Serilog Extensions Logging

serilog / Serilog Extensions Logging

Licence: apache-2.0
Serilog provider for Microsoft.Extensions.Logging

Projects that are alternatives of or similar to Serilog Extensions Logging

Revo
Event Sourcing, CQRS and DDD framework for C#/.NET Core.
Stars: ✭ 162 (-24.65%)
Mutual labels:  aspnetcore
Aspnetcore.identity.mongo
This is a MongoDB provider for the ASP.NET Core 2 Identity framework
Stars: ✭ 179 (-16.74%)
Mutual labels:  aspnetcore
Blazorrepl
Write, compile, execute and share Blazor components entirely in the browser
Stars: ✭ 196 (-8.84%)
Mutual labels:  aspnetcore
Aspnet Api Versioning
Provides a set of libraries which add service API versioning to ASP.NET Web API, OData with ASP.NET Web API, and ASP.NET Core.
Stars: ✭ 2,154 (+901.86%)
Mutual labels:  aspnetcore
Aspnetcoreangularsignalrsecurity
Security with ASP.NET Core, SignalR and Angular
Stars: ✭ 171 (-20.47%)
Mutual labels:  aspnetcore
Aspnetcorelocalization
Localization.SqlLocalizer & ASP.NET Core MVC Localization Examples
Stars: ✭ 183 (-14.88%)
Mutual labels:  aspnetcore
Firewall
ASP.NET Core middleware for IP address filtering.
Stars: ✭ 159 (-26.05%)
Mutual labels:  aspnetcore
Aspnetcore Vue Typescript Template
Template AspNetCore with Vue, Vue router, Vuex, TypeScript, Bulma, Sass and Jest
Stars: ✭ 215 (+0%)
Mutual labels:  aspnetcore
Aspnet Core 3 Registration Login Api
ASP.NET Core 3.1 API for User Management, Authentication and Registration
Stars: ✭ 173 (-19.53%)
Mutual labels:  aspnetcore
Onion Architecture Asp.net Core
WhiteApp API solution template which is built on Onion Architecture with all essential feature using .NET 5!
Stars: ✭ 196 (-8.84%)
Mutual labels:  aspnetcore
Architecture
.NET 6, ASP.NET Core 6, Entity Framework Core 6, C# 10, Angular 13, Clean Code, SOLID, DDD.
Stars: ✭ 2,285 (+962.79%)
Mutual labels:  aspnetcore
Abp.wechat
Abp 微信 SDK 模块,包含对微信小程序、公众号、企业微信、开放平台、第三方平台等相关接口封装。
Stars: ✭ 168 (-21.86%)
Mutual labels:  aspnetcore
Aspnetcoremultipleproject
ASP.NET Core API EF Core and Swagger
Stars: ✭ 189 (-12.09%)
Mutual labels:  aspnetcore
Netcorecms
NetCoreCMS is a modular theme supported Content Management System developed using ASP.Net Core 2.0 MVC. Which is also usable as web application framework. This project is still under development. Please do not use before it's first release.
Stars: ✭ 165 (-23.26%)
Mutual labels:  aspnetcore
Aspnetcore.identity.mongodb
MongoDB Data Store Adaptor for ASP.NET Core Identity
Stars: ✭ 210 (-2.33%)
Mutual labels:  aspnetcore
Aspnetcoreangularsignalr
SignalR ASP.NET Core Angular
Stars: ✭ 163 (-24.19%)
Mutual labels:  aspnetcore
Organizingaspnetcore
Offers several different ways to organize content in ASP.NET Core MVC and Razor Pages projects.
Stars: ✭ 183 (-14.88%)
Mutual labels:  aspnetcore
Openiddict Samples
ASP.NET Core, Microsoft.Owin/ASP.NET 4.x and JavaScript samples for OpenIddict
Stars: ✭ 214 (-0.47%)
Mutual labels:  aspnetcore
Run Aspnetcore Realworld
E-Commerce real world example of run-aspnetcore ASP.NET Core web application. Implemented e-commerce domain with clean architecture for ASP.NET Core reference application, demonstrating a layered application architecture with DDD best practices. Download 100+ page eBook PDF from here ->
Stars: ✭ 208 (-3.26%)
Mutual labels:  aspnetcore
Parbad
A free, open-source, integrated and extensible library which connects your web applications to online payment gateways. Gateways can be added or developed by you.
Stars: ✭ 194 (-9.77%)
Mutual labels:  aspnetcore

Serilog.Extensions.Logging Build status NuGet Version

A Serilog provider for Microsoft.Extensions.Logging, the logging subsystem used by ASP.NET Core.

ASP.NET Core Instructions

ASP.NET Core applications should prefer Serilog.AspNetCore and UseSerilog() instead.

Non-web .NET Core Instructions

Non-web .NET Core applications should prefer Serilog.Extensions.Hosting and UseSerilog() instead.

.NET Core 1.0, 1.1 and Default Provider Integration

The package implements AddSerilog() on ILoggingBuilder and ILoggerFactory to enable the Serilog provider under the default Microsoft.Extensions.Logging implementation.

First, install the Serilog.Extensions.Logging NuGet package into your web or console app. You will need a way to view the log messages - Serilog.Sinks.Console writes these to the console.

Install-Package Serilog.Extensions.Logging -DependencyVersion Highest
Install-Package Serilog.Sinks.Console

Next, in your application's Startup method, configure Serilog first:

using Serilog;

public class Startup
{
  public Startup(IHostingEnvironment env)
  {
    Log.Logger = new LoggerConfiguration()
      .Enrich.FromLogContext()
      .WriteTo.Console()
      .CreateLogger();
      
    // Other startup code

Finally, for .NET Core 2.0+, in your Startup class's Configure() method, remove the existing logger configuration entries and call AddSerilog() on the provided loggingBuilder.

  public void ConfigureServices(IServiceCollection services)
  {
      services.AddLogging(loggingBuilder =>
      	loggingBuilder.AddSerilog(dispose: true));
      
      // Other services ...
  }

For .NET Core 1.0 or 1.1, in your Startup class's Configure() method, remove the existing logger configuration entries and call AddSerilog() on the provided loggerFactory.

  public void Configure(IApplicationBuilder app,
                        IHostingEnvironment env,
                        ILoggerFactory loggerfactory,
                        IApplicationLifetime appLifetime)
  {
      loggerfactory.AddSerilog();
      
      // Ensure any buffered events are sent at shutdown
      appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

That's it! With the level bumped up a little you should see log output like:

[22:14:44.646 DBG] RouteCollection.RouteAsync
	Routes: 
		Microsoft.AspNet.Mvc.Routing.AttributeRoute
		{controller=Home}/{action=Index}/{id?}
	Handled? True
[22:14:44.647 DBG] RouterMiddleware.Invoke
	Handled? True
[22:14:45.706 DBG] /lib/jquery/jquery.js not modified
[22:14:45.706 DBG] /css/site.css not modified
[22:14:45.741 DBG] Handled. Status code: 304 File: /css/site.css

Notes on Log Scopes

Microsoft.Extensions.Logging provides the BeginScope API, which can be used to add arbitrary properties to log events within a certain region of code. The API comes in two forms:

  1. The method: IDisposable BeginScope<TState>(TState state)
  2. The extension method: IDisposable BeginScope(this ILogger logger, string messageFormat, params object[] args)

Using the extension method will add a Scope property to your log events. This is most useful for adding simple "scope strings" to your events, as in the following code:

using (_logger.BeginScope("Transaction")) {
    _logger.LogInformation("Beginning...");
    _logger.LogInformation("Completed in {DurationMs}ms...", 30);
}
// Example JSON output:
// {"@t":"2020-10-29T19:05:56.4126822Z","@m":"Beginning...","@i":"f6a328e9","SourceContext":"SomeNamespace.SomeService","Scope":["Transaction"]}
// {"@t":"2020-10-29T19:05:56.4176816Z","@m":"Completed in 30ms...","@i":"51812baa","DurationMs":30,"SourceContext":"SomeNamespace.SomeService","Scope":["Transaction"]}

If you simply want to add a "bag" of additional properties to your log events, however, this extension method approach can be overly verbose. For example, to add TransactionId and ResponseJson properties to your log events, you would have to do something like the following:

// WRONG! Prefer the dictionary approach below instead
using (_logger.BeginScope("TransactionId: {TransactionId}, ResponseJson: {ResponseJson}", 12345, jsonString)) {
    _logger.LogInformation("Completed in {DurationMs}ms...", 30);
}
// Example JSON output:
// {
//	"@t":"2020-10-29T19:05:56.4176816Z",
//	"@m":"Completed in 30ms...",
//	"@i":"51812baa",
//	"DurationMs":30,
//	"SourceContext":"SomeNamespace.SomeService",
//	"TransactionId": 12345,
//	"ResponseJson": "{ \"Key1\": \"Value1\", \"Key2\": \"Value2\" }",
//	"Scope":["TransactionId: 12345, ResponseJson: { \"Key1\": \"Value1\", \"Key2\": \"Value2\" }"]
// }

Not only does this add the unnecessary Scope property to your event, but it also duplicates serialized values between Scope and the intended properties, as you can see here with ResponseJson. If this were "real" JSON like an API response, then a potentially very large block of text would be duplicated within your log event! Moreover, the template string within BeginScope is rather arbitrary when all you want to do is add a bag of properties, and you start mixing enriching concerns with formatting concerns.

A far better alternative is to use the BeginScope<TState>(TState state) method. If you provide any IEnumerable<KeyValuePair<string, object>> to this method, then Serilog will output the key/value pairs as structured properties without the Scope property, as in this example:

var scopeProps = new Dictionary<string, object> {
    { "TransactionId", 12345 },
    { "ResponseJson", jsonString },
};
using (_logger.BeginScope(scopeProps) {
    _logger.LogInformation("Transaction completed in {DurationMs}ms...", 30);
}
// Example JSON output:
// {
//	"@t":"2020-10-29T19:05:56.4176816Z",
//	"@m":"Completed in 30ms...",
//	"@i":"51812baa",
//	"DurationMs":30,
//	"SourceContext":"SomeNamespace.SomeService",
//	"TransactionId": 12345,
//	"ResponseJson": "{ \"Key1\": \"Value1\", \"Key2\": \"Value2\" }"
// }

Credits

This package evolved from an earlier package Microsoft.Framework.Logging.Serilog provided by the ASP.NET team.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].