[WPF] EntityframeworkCore NLog output settings

Recently with EFcore, since they are unfamiliar, often do not know how to troubleshoot some anomalies, only the execution of recording EFcore print out the investigation. Indeed simplifies the investigation of many problems.

Official website provides Asp.net Core configuration and .net core application, indicating just not WPF and other applications. This chapter as a supplement for your reference.

Because I use Prism + PostgreSQL + Nlog, all contribute here only about Nlog method of EntityframeworkCore.

The required installation package

  • NLog
  • NLog.Extensions.Logging
  • Npgsql.EntityFrameworkCore.PostgreSQL

Dependency injection is provided

App.xaml.cs

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<Login>(Authentication.LoginURL);
            containerRegistry.Register<ILoggerFactory, NLog.Extensions.Logging.NLogLoggerFactory>();
        }

NLogLoggerFactory default creates a new NLogLoggerProvider.

NLog.config Configuration

This is a personal favorite configuration, for reference purposes only.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true">

  <variable name="loglayout" value="${longdate}|${level:uppercase=true}|${message}  ${exception:format=tostring}"/>
  <targets async="true">
    <target name="infologfile" xsi:type="File" fileName="logs/Info.${shortdate}.log" 
            layout="${loglayout}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="debuglogfile" />
  </rules>
</nlog>
async = "true" asynchronous update log. Logs folder is created by default a log stored in exe executable file folders.

 

 DbContext Configuration

Due to the use DI, only we need to pass ILoggerFactory can be in the constructor inside.

    public class PsqlDbContext : DbContext, IDbContext
    {

        private readonly ILoggerFactory _factory;

        public PsqlDbContext(ILoggerFactory loggerFactory)
        {
            _factory = loggerFactory;
        }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseLoggerFactory(_factory)
                .EnableSensitiveDataLogging()
                .UseNpgsql("ProstgreSqlConnectStringxxxxx");
        }

This set is complete.

Examples Screenshot

 

 Those executed sql, execute timeout are clear.

 

Guess you like

Origin www.cnblogs.com/lixiaobin/p/postgresqlefcorenlog.html