2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

EF Coreで簡単なログ出力(SQL文の出力)

Last updated at Posted at 2022-10-09

はじめに

この記事では、EF Coreで簡単なログ出力をしてみます。デバッグ時に、出力ウインドにSQL文が出力されるようにします。

動作確認は、

  • オンプレのWindows Server 2016
  • SQL Server 2017
  • .NET6
  • Visual Studio 2022
  • Microsoft.EntityFrameworkCore.SqlServer のインストール

で行いました。

LogToメソッドで出力ウインドに出力

DbContext派生クラスのOnConfiguringメソッド内に、DbContextOptionsBuilderクラスのLogToメソッドを書いて、ログの出力先や出力内容を設定します。

HogeContext.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

 internal class HogeContext : DbContext
    {
        private readonly string connectionString;
        public HogeContext()
        {
            connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=HogeDb;Trusted_Connection=True;";
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                // ここに注目
                .LogTo(
                    message => Debug.WriteLine(message),
                    new[] { DbLoggerCategory.Database.Name },
                    LogLevel.Debug, 
                    DbContextLoggerOptions.LocalTime)
                .UseSqlServer(connectionString);
        }

        // DbSetの例
        public DbSet<Person> People { get; set; }
        public DbSet<Pet> Pets { get; set; }
    }
}

以下は、LogToメソッドの引数の設定内容の説明です。

  • 第一引数 message => Debug.WriteLine(message)
    ここで出力ウインドに出力するように設定。

  • 第二引数 new[] { DbLoggerCategory.Database.Name }
    ログ・メッセージのカテゴリをDataBase.Nameに設定。こうすることで、Database.ConnectionDatabase.CommandDatabase.Transaction などのデータベース関連のサブカテゴリのメッセージを取得できる。

  • 第三引数 LogLevel.Debug
    ログ・レベルを設定。他にLogLevel.Informationなどがある。

  • 第四引数 DbContextLoggerOptions.LocalTime
    個々のメッセージに冠されるタイトル行の表示内容を設定。ここでは日時のみに省略するようにしています。

LogToメソッドは、これも含めて5つオーバーロードが定義されている。(2022/10/10 現在)
より詳しくは、Microsoft Learn の「シンプルなログ」を参照ください。

EFCoreを利用しているとログの確認がしたくなります。
自分が書いたメソッド式やクエリ式でどの様なSQL文が生成されているか。
コードを書き換えることでSQL文がどう変化するか。
SQL文以外にもDataReaderやConnectionが開いたり閉じたりする様子もわかり、見ていると色々と気付かされます。:smile:

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?