Last active
September 17, 2017 10:55
-
-
Save ichiroku11/97c54efa64c9727690edf8017788f1d3 to your computer and use it in GitHub Desktop.
EF Coreでログ出力
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use Test; | |
| drop table if exists dbo.Monster; | |
| create table dbo.Monster( | |
| Id int, | |
| Name nvarchar(20), | |
| constraint PK_Monster primary key(Id) | |
| ); | |
| insert into dbo.Monster(Id, Name) | |
| output inserted.* | |
| values | |
| (1, N'スライム'), | |
| (2, N'ドラキー'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Data.SqlClient; | |
| using System.Linq; | |
| using Microsoft.EntityFrameworkCore; | |
| using Microsoft.EntityFrameworkCore.Infrastructure; | |
| using Microsoft.Extensions.DependencyInjection; | |
| using Microsoft.Extensions.Logging; | |
| using Microsoft.Extensions.Logging.Abstractions; | |
| namespace ConsoleApp { | |
| // ロガープロバイダー | |
| public class AppLoggerProvider : ILoggerProvider { | |
| // ロガーを生成 | |
| public ILogger CreateLogger(string categoryName) { | |
| // SQLの実行に関するログだけ出力する | |
| if (string.Equals(categoryName, DbLoggerCategory.Database.Command.Name)) { | |
| return new ConsoleLogger(); | |
| } | |
| // 何も出力しないロガー | |
| return NullLogger.Instance; | |
| } | |
| public void Dispose() { | |
| } | |
| // ロガー | |
| private class ConsoleLogger : ILogger { | |
| public IDisposable BeginScope<TState>(TState state) => null; | |
| public bool IsEnabled(LogLevel logLevel) => true; | |
| // ログを書き込む | |
| public void Log<TState>( | |
| LogLevel logLevel, EventId eventId, | |
| TState state, Exception exception, | |
| Func<TState, Exception, string> formatter) { | |
| // ログをコンソールに出力 | |
| // LogLevelとEventIdも出力してみる | |
| Console.WriteLine($"{nameof(logLevel)}: {logLevel}"); | |
| Console.WriteLine($"{nameof(eventId)}: {eventId}"); | |
| Console.WriteLine(formatter(state, exception)); | |
| Console.WriteLine("---"); | |
| } | |
| } | |
| } | |
| // エンティティ(モンスター) | |
| public class Monster { | |
| public int Id { get; set; } | |
| public string Name { get; set; } | |
| } | |
| // DBコンテキスト | |
| public class AppDbContext : DbContext { | |
| public DbSet<Monster> Monsters { get; set; } | |
| protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { | |
| // 接続文字列を指定する | |
| var connectionString = new SqlConnectionStringBuilder { | |
| DataSource = ".", | |
| InitialCatalog = "Test", | |
| IntegratedSecurity = true, | |
| }.ToString(); | |
| optionsBuilder.UseSqlServer(connectionString); | |
| } | |
| protected override void OnModelCreating(ModelBuilder modelBuilder) { | |
| // テーブルにマッピングする | |
| modelBuilder.Entity<Monster>().ToTable("Monster"); | |
| } | |
| } | |
| class Program { | |
| static void Main(string[] args) { | |
| using (var dbContext = new AppDbContext()) { | |
| // ロガープロバイダーを設定する | |
| var serviceProvider = dbContext.GetInfrastructure(); | |
| var loggerFactory = serviceProvider.GetService<ILoggerFactory>(); | |
| loggerFactory.AddProvider(new AppLoggerProvider()); | |
| // データを取得 | |
| var monsters = dbContext.Monsters.ToList(); | |
| foreach (var monster in monsters) { | |
| Console.WriteLine($"#{monster.Id} {monster.Name}"); | |
| } | |
| //#1 スライム | |
| //#2 ドラキー | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment