首页 > Windows开发 > 详细

【WPF】EntityframeworkCore NLog出力设置

时间:2019-10-13 21:13:36      阅读:99      评论:0      收藏:0      [点我收藏+]

最近在用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,执行超时时间都一目了然。

 

【WPF】EntityframeworkCore NLog出力设置

原文:https://www.cnblogs.com/lixiaobin/p/postgresqlefcorenlog.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!