All Projects → msmolka → Znetcs.aspnetcore.logging.entityframeworkcore

msmolka / Znetcs.aspnetcore.logging.entityframeworkcore

Licence: mit
This is Entity Framework Core logger and logger provider. A small package to allow store logs in any data store using Entity Framework Core.

Projects that are alternatives of or similar to Znetcs.aspnetcore.logging.entityframeworkcore

MinimalApi
ASP.NET Core 7.0 - Minimal API Example - Todo API implementation using ASP.NET Core Minimal API, Entity Framework Core, Token authentication, Versioning, Unit Testing, Integration Testing and Open API.
Stars: ✭ 156 (+550%)
Mutual labels:  aspnetcore, entity-framework-core, aspnet-core, asp-net-core
TheLastTime
C# .NET 5 Blazor WebAssembly Progressive Web Application that tracks when was the last time you did something
Stars: ✭ 23 (-4.17%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
Asp.net Core Template
A ready-to-use template for ASP.NET Core with repositories, services, models mapping, DI and StyleCop warnings fixed.
Stars: ✭ 599 (+2395.83%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core
Awesome-Nuget-Packages
📦 A collection of awesome and top .NET packages sorted by most popular needs.
Stars: ✭ 87 (+262.5%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
Home
Home for Blazor Extensions
Stars: ✭ 51 (+112.5%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
AspNetCore.Unobtrusive.Ajax
Unobtrusive Ajax Helpers (like MVC5 Ajax.BeignForm and Ajax.ActionLink) for ASP.NET Core
Stars: ✭ 46 (+91.67%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
Aspnetcore Developer Roadmap
Roadmap to becoming an ASP.NET Core developer in 2021
Stars: ✭ 8,248 (+34266.67%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core
SeoTags
SeoTags create all SEO tags you need such as meta, link, twitter card (twitter:), open graph (og:), and JSON-LD schema (structred data).
Stars: ✭ 113 (+370.83%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
DNZ.MvcComponents
A set of useful UI-Components (HtmlHelper) for ASP.NET Core MVC based-on Popular JavaScript Plugins (Experimental project).
Stars: ✭ 25 (+4.17%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
ChatService
ChatService (SignalR).
Stars: ✭ 26 (+8.33%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
awesome-dotnet-async
A curated list of awesome articles and resources to learning and practicing about async, threading, and channels in .Net platform. 😉
Stars: ✭ 84 (+250%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
Practical Aspnetcore
Practical samples of ASP.NET Core 2.1, 2.2, 3.1, 5.0 and 6.0 projects you can use. Readme contains explanations on all projects.
Stars: ✭ 6,199 (+25729.17%)
Mutual labels:  asp-net-core, aspnetcore, aspnet-core
Jslogger
Integrate JavaScript Logging with ASP.NET Core Logging APIs
Stars: ✭ 19 (-20.83%)
Mutual labels:  aspnetcore, logging, logger
OnlineUsers-Counter-AspNetCore
Display online users count in ASP.NET Core in two ways (Cookie - SingalR)
Stars: ✭ 29 (+20.83%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
Hexagonal-architecture-ASP.NET-Core
App generator API solution template which is built on Hexagnonal Architecture with all essential feature using .NET Core
Stars: ✭ 57 (+137.5%)
Mutual labels:  aspnetcore, entity-framework-core, asp-net-core
high-performance-aspnet-core-workshop
Sample application used in the High-Performance ASP.NET Core Workshop
Stars: ✭ 29 (+20.83%)
Mutual labels:  aspnetcore, aspnet-core, asp-net-core
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 (+766.67%)
Mutual labels:  entity-framework-core, aspnetcore, aspnet-core
Run Aspnetcore
A starter kit for your next ASP.NET Core web application. Boilerplate for ASP.NET Core reference application, demonstrating a layered application architecture with applying Clean Architecture and DDD best practices. Download 100+ page eBook PDF from here ->
Stars: ✭ 227 (+845.83%)
Mutual labels:  entity-framework-core, aspnetcore, aspnet-core
run-aspnetcore-basics retired
One Solution - One Project for web application development with Asp.Net Core & EF.Core. Only one web application project which used aspnetcore components; razor pages, middlewares, dependency injection, configuration, logging. To create websites with minimum implementation of asp.net core based on HTML5, CSS, and JavaScript. You can use this boi…
Stars: ✭ 15 (-37.5%)
Mutual labels:  aspnetcore, entity-framework-core, aspnet-core
Simplcommerce
A simple, cross platform, modularized ecommerce system built on .NET Core
Stars: ✭ 3,474 (+14375%)
Mutual labels:  entity-framework-core, asp-net-core, aspnetcore

ZNetCS.AspNetCore.Logging.EntityFrameworkCore

NuGet

This is Entity Framework Core logger and logger provider. A small package to allow store logs in any data store using Entity Framework Core. It was prepared to use in ASP NET Core application, but it does not contain any references that prevents to use it in plain .NET Core application.

Installing

Install using the ZNetCS.AspNetCore.Logging.EntityFrameworkCore NuGet package

PM> Install-Package ZNetCS.AspNetCore.Logging.EntityFrameworkCore

Usage

When you install the package, it should be added to your .csproj. Alternatively, you can add it directly by adding:

<ItemGroup>
    <PackageReference Include="ZNetCS.AspNetCore.Logging.EntityFrameworkCore" Version="2.1.0" />
</ItemGroup>

As from ASP.NET Core 2.0 version, the configuration of logging was changed. Now it should be configure with WebHostBuilder See: Introduction to logging in ASP.NET Core for more details.

As from version 2.0.2 there is silent error handling on logger SaveChanges(). To avoid Db error having impact on application.

using ZNetCS.AspNetCore.Logging.EntityFrameworkCore;
...
public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        // other code ommited to focus on logging settings
        .ConfigureLogging((hostingContext, logging) =>
        {
            // other log providers
            // ...
            //
            logging.AddEntityFramework<MyDbContent>();

        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

Important Notes

In most case scenario you would not like add all logs from application to database. A lot of of them is jut debug/trace ones. In that case is better use filter before add Logger. This will also prevent some StackOverflowException when using this logger to log EntityFrameworkCore logs.

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        // other code ommited to focus on logging settings
        .ConfigureLogging((hostingContext, logging) =>
        {
            // other log providers
            // ...
            //

            // because setting up filter inside code requires exact provider class, and EntityFrameworkLoggerProvider is generic class with multiple overrides
            // filters needs to applied properly to chosen provider
            logging.AddFilter<EntityFrameworkLoggerProvider<MyDbContent>>("Microsoft", LogLevel.None);
            logging.AddFilter<EntityFrameworkLoggerProvider<MyDbContent>>("System", LogLevel.None);
            logging.AddEntityFramework<MyDbContent>();

        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

It is also possible to setting filters inside appsettings.json file. This provider is using EntityFramework alias. This way is recommended because there is no need to care about proper provider definition.

{
  "Logging": {
    "EntityFramework": {
      "LogLevel": {
        "Microsoft": "None",
        "System": "None"
      }
    }
  }
}
public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        // other code ommited to focus on logging settings
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));

            // other log providers
            // ...
            //

            logging.AddEntityFramework<MyDbContent>();

        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

Then you need to setup your context to have access to log table e.g.

using ZNetCS.AspNetCore.Logging.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions options) : base(options)
    {
    }
   
    public DbSet<Log> Logs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // build default model.
        LogModelBuilderHelper.Build(modelBuilder.Entity<Log>());

        // real relation database can map table:
        modelBuilder.Entity<Log>().ToTable("Log");
    }   
}

There is also possibilty to extend base Log class.

public class ExtendedLog : Log
{
    public ExtendedLog(IHttpContextAccessor accessor)
    {          
        string browser = accessor.HttpContext.Request.Headers["User-Agent"];
        if (!string.IsNullOrEmpty(browser) && (browser.Length > 255))
        {
            browser = browser.Substring(0, 255);
        }

        this.Browser = browser;
        this.Host = accessor.HttpContext.Connection?.RemoteIpAddress?.ToString();
        this.User = accessor.HttpContext.User?.Identity?.Name;
        this.Path = accessor.HttpContext.Request.Path;
    }

    protected ExtendedLog()
    {
    }
      
    public string Browser { get; set; }
    public string Host { get; set; }
    public string Path { get; set; }
    public string User { get; set; }
}

Change MyDbContext to use new extended log model

public DbSet<ExtendedLog> Logs { get; set; }

You can extend ModelBuilder as well:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // build default model.
    LogModelBuilderHelper.Build(modelBuilder.Entity<ExtendedLog>());

    // real relation database can map table:
    modelBuilder.Entity<ExtendedLog>().ToTable("Log");

    modelBuilder.Entity<ExtendedLog>().Property(r => r.Id).ValueGeneratedOnAdd();

    modelBuilder.Entity<ExtendedLog>().HasIndex(r => r.TimeStamp).HasName("IX_Log_TimeStamp");
    modelBuilder.Entity<ExtendedLog>().HasIndex(r => r.EventId).HasName("IX_Log_EventId");
    modelBuilder.Entity<ExtendedLog>().HasIndex(r => r.Level).HasName("IX_Log_Level");

    modelBuilder.Entity<ExtendedLog>().Property(u => u.Name).HasMaxLength(255);
    modelBuilder.Entity<ExtendedLog>().Property(u => u.Browser).HasMaxLength(255);
    modelBuilder.Entity<ExtendedLog>().Property(u => u.User).HasMaxLength(255);
    modelBuilder.Entity<ExtendedLog>().Property(u => u.Host).HasMaxLength(255);
    modelBuilder.Entity<ExtendedLog>().Property(u => u.Path).HasMaxLength(255);
}   

To use IHttpContextAccessor there is need to register it inside ConfigureServices call of Startup:

public void ConfigureServices(IServiceCollection services)
{
    // requires for http context access.
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

Add extended log registration

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        // other code ommited to focus on logging settings
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));

            // other log providers
            // ...
            //

            logging.AddEntityFramework<MyDbContent, ExtendedLog>();

        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

There is also possibility to create new log model using custom creator method. This can be done by providing options during configuration.

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        // other code ommited to focus on logging settings
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));

            // other log providers
            // ...
            //

            logging.AddEntityFramework<MyDbContent>(
                opts =>
                {
                    opts.Creator = (logLevel, eventId, name, message) => new Log
                    {
                        TimeStamp = DateTimeOffset.Now,
                        Level = logLevel,
                        EventId = eventId,
                        Name = "This is my custom log",
                        Message = message
                    };
                });

        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

Below configuration is still compatible with 2.0, but currently recommended way to configure logging is to use Web Host Builder.

In order to use the Entity Framework Logger Provider, you must configure the logger factory in Configure call of Startup:

using ZNetCS.AspNetCore.Logging.EntityFrameworkCore;
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // MyDbContext is registered in ConfigureServices Entity Framework Core application context
    loggerFactory.AddEntityFramework<MyDbContent>(app.ApplicationServices);

    // other middleware e.g. MVC etc
}

For filtering with ILoggerFactory there is required to install Microsoft.Extensions.Logging.Filter package (which is now deprecated).

PM> Install-Package  Microsoft.Extensions.Logging.Filter;
    loggerFactory
        .WithFilter(
            new FilterLoggerSettings
            {
                { "Microsoft", LogLevel.None },
                { "System", LogLevel.None }
            })
        .AddEntityFramework<MyDbContent>(app.ApplicationServices);

For using extended logging change in Configure call of Startup:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // MyDbContext is registered in ConfigureServices Entity Framework Core application context
    loggerFactory.AddEntityFramework<MyDbContext, ExtendedLog>(app.ApplicationServices);

    // other middleware e.g. MVC etc
}

Usage of ustom creator method (without resolving dependencies). This can be done by extending loggerFactory.AddEntityFramework call.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // MyDbContext is registered in ConfigureServices Entity Framework Core application context
    loggerFactory 
        .AddEntityFramework<MyDbContext>(
            app.ApplicationServices,
            creator: (logLevel, eventId, name, message) => new Log
            {
                TimeStamp = DateTimeOffset.Now,
                Level = logLevel,
                EventId = eventId,
                Name = "This is my custom log",
                Message = message
            });

    // other middleware e.g. MVC etc
}
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].