【WPF】EntityframeworkCore NLog出力設置


最近在用EFcore,由於不熟悉,經常出現一些異常都不知道如何排查,只能把EFcore的執行記錄打印出來調查。確實簡化了很多問題的調查。

官網提供了Asp.net Core與.net core 應用的配置,唯獨沒有WPF等應用的說明。本章作為一個補充,供各位參考。

由於我用的是Prism+PostgreSQL+Nlog,所有這里只講述EntityframeworkCore的Nlog出力方法。

所需安裝包

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

依賴注入設置

App.xaml.cs

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

NLogLoggerFactory默認會創建一個新的NLogLoggerProvider。

NLog.config配置

這是個人喜歡的配置,僅供參考。

<?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"非同期更新日志。默認在exe執行文件夾下創建一個Logs文件夾存放日志。

 

 DbContext配置

由於使用了DI,只需要在構造函數里面傳入ILoggerFactory就可以。

    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");
        }

這樣就設置完成了。

實例截圖

 

 執行了那些sql,執行超時時間都一目了然。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM