EF Core如何输出日志到Visual Studio的输出窗口

我们在使用EF Core的时候,很多时候需要在Visual Studio的输出窗口中知道EF Core在后台生成的SQL语句是什么,这个需求可以通过自定义EF Core的ILoggerFactory和ILogger类来实现:

首先定义一个实现了ILogger接口的类EFLogger,主要目的是将EF Core生成的Log信息输出到Visual Studio的输出窗口:

using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;

namespace WebCore.Utils
{
    public class EFLogger : ILogger
    {
        protected string categoryName;

        public EFLogger(string categoryName)
        {
            this.categoryName = categoryName;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            //通过Debugger.Log方法来将EF Core生成的Log信息输出到Visual Studio的输出窗口
            Debugger.Log(0, categoryName, "=============================== EF Core log started ===============================\r\n");
            Debugger.Log(0, categoryName, formatter(state,exception)+"\r\n");
            Debugger.Log(0, categoryName, "=============================== EF Core log finished ===============================\r\n");
        }
    }
}

然后定义一个实现了ILoggerFactory接口的类EFLoggerFactory,用于创建上面定义的EFLogger类的实例:

using Microsoft.Extensions.Logging;

namespace WebCore.Utils
{
    public class EFLoggerFactory : ILoggerFactory
    {
        public void AddProvider(ILoggerProvider provider)
        {
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new EFLogger(categoryName);//创建EFLogger类的实例
        }

        public void Dispose()
        {

        }
    }
}

最后在DbContext的OnConfiguring方法中,调用optionsBuilder.UseLoggerFactory来将EFLoggerFactory类的实例注入给EF Core,这样所有DbContext的Log信息,都会由EFLogger类输出到Visual Studio的输出窗口了。

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using WebCore.Utils;

namespace WebCore.Entities
{
    public partial class TestDBContext : DbContext
    {
        public TestDBContext()
        {
            this.Database.SetCommandTimeout(0);//设置SqlCommand永不超时
        }

        public TestDBContext(DbContextOptions<TestDBContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Person> Person { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseLoggerFactory(new EFLoggerFactory());//将EFLoggerFactory类的实例注入给EF Core,这样所有DbContext的Log信息,都会由EFLogger类输出到Visual Studio的输出窗口了
                optionsBuilder.UseSqlServer("Server=localhost;User Id=sa;Password=1qaz!QAZ;Database=TestDB");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //省略代码...
        }
    }
}
        

注意OnConfiguring这个方法是virtual的,所以我们也可以选择在DbContext的子类中来重写这个方法,在子类的OnConfiguring中注入EFLoggerFactory类的实例到DbContext。

最后我们来看看EF Core日志输出的效果,还是很规整的,最重要的是我们可以实时的得到EF Core在后台生成的SQL语句:

原文地址:https://www.cnblogs.com/OpenCoder/p/9769455.html

时间: 2024-07-31 05:39:06

EF Core如何输出日志到Visual Studio的输出窗口的相关文章

ASP.NET Core + Angular 2 Template for Visual Studio

多个月以来,我和多个Github上的社区贡献者一起建立支持库.包,我们最终的目的是希望完成这样一个作为起点的模板,也就是基于把Typescript代码和Angular2宿主在ASP.NET Core项目中,这个模板包含一下这些方面: 服务端预加载(预渲染):这样你的UI可以快速的显示,甚至在浏览器下载Javascript之前. Webpack中间件集成:在开发期间,你不需要一直重新编译你的客户端项目,或者你可以用一个watcher工具在后台帮你做这些事. 模块热拔插:在开发期间,一旦你编辑了一个

使用Visual Studio开发ASP.NET Core MVC and Entity Framework Core初学者教程

原文地址:https://docs.asp.net/en/latest/data/ef-mvc/intro.html The Contoso University sample web application demonstrates how to create ASP.NET Core 1.0 MVC web applications using Entity Framework Core 1.0 and Visual Studio 2015. Contoso University网络应用的案

【目录】开始使用ASP.NET Core MVC和Visual Studio

参照微软教程:Building your first ASP.NET Core MVC app with Visual Studio This series of tutorials will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio. Getting started Adding a controller Adding a view Adding a model Workin

.NET Core Tools for Visual Studio 2015 安装失败

You may be blocked from installing the .NET Core Tooling Preview 2 for Visual Studio 2015 installer due to a temporary bug. To workaround it, run the installer from the commandline with theSKIP_VSU_CHECK=1 argument, as you see in the example below. D

Getting started with ASP.NET Core MVC and Visual Studio

This tutorial will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio 2015. https://docs.asp.net/en/latest/tutorials/first-mvc-app/start-mvc.html

005.Getting started with ASP.NET Core MVC and Visual Studio -- 【VS开发asp.net core mvc 入门】

Getting started with ASP.NET Core MVC and Visual Studio VS开发asp.net core mvc 入门 2017-3-7 2 分钟阅读时长 本文内容 1.Install Visual Studio and .NET Core 安装 VS 与 .NET Core 2.Create a web app 创建一个 web 应用 By Rick Anderson This tutorial will teach you the basics of

DevExpress ASP.NET Core v19.1版本亮点:Visual Studio集成

行业领先的.NET界面控件DevExpress 发布了v19.1版本,本文将以系列文章的方式为大家介绍DevExpress ASP.NET Core Controls v19.1中新增的一些控件及增强的控件功能,欢迎下载v19.1试用,点击立即下载>> UI小部件 全新的下拉按钮小部件 19.1引入一个带有内置下拉菜单的新按钮小部件,此窗口小部件可用作无状态可点击菜单项集,也可用作SelectBox控件(看起来像按钮)的有状态模拟. 新的浮动按钮小部件 新的浮动按钮小部件是一个位于屏幕底角的单

有感 Visual Studio 2015 RTM 简介 - 八年后回归 Dot Net,终于迎来了 Mvc 时代,盼走了 Web 窗体时代

有感 Visual Studio 2015 RTM 简介 - 八年后回归 Dot Net,终于迎来了 Mvc 时代,盼走了 Web 窗体时代 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. 关于

Visual Studio调试之断点进阶篇

Visual Studio调试之断点进阶篇 在上一篇文章Visual Studio调试之断点基础篇里面介绍了什么是断点,INT 是Intel系列CPU的一个指令,可以让程序产生一个中断或者异常.程序中如果有中断或者异常发生了以后,CPU会中断程序的执行,去一个叫做IDT的部件查找处理这个中断(或者异常)的例程(Handler).IDT是操作系统在启动的时候初始化的,至于IDT的细节问题,例如什么是IDT,怎样编写一个IDT的例程,怎样 初始化IDT,可以去网上搜索一些资料. 总之,这里我们只要知