using dotNET.Core;
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace dotNET.EFCoreRepository { /// <summary> /// ef 日志 /// </summary> public class EFLoggerProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) => new EFLogger(categoryName); public void Dispose() { } } /// <summary> /// /// </summary> public class EFLogger : ILogger { private readonly string categoryName; public EFLogger(string categoryName) => this.categoryName = categoryName; public bool IsEnabled(LogLevel logLevel) => true; public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { //categoryName when performing database queries ef core Microsoft.EntityFrameworkCore.Database.Command, logging level Information IF (categoryName == " Microsoft.EntityFrameworkCore.Database.Command " && the logLevel == LogLevel.Information) { var logContent = Formatter (State , Exception); NLogger.Debug (logContent); // TraceMessage ( "Something Happened."); // NLogger.Info (GetCodeLineAndFileName ()); // TODO: how to get the contents of the log wanted to play on how to play Console. the WriteLine (); the Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(logContent); Console.ResetColor(); } } public IDisposable BeginScope<TState>(TState state) => null; public void TraceMessage(string message, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "", [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) { NLogger.Debug("message: " + message); NLogger.Debug("member name: " + memberName); NLogger.Debug("source file path: " + sourceFilePath); NLogger.Debug("source line number: " + sourceLineNumber); } public string GetCodeLineAndFileName() { StackTrace insStackTrace = new StackTrace(true); var insStackFrames = insStackTrace.GetFrames(); string str = ""; foreach(var insStackFrame in insStackFrames) { str += String.Format("\nFile: {0}, Line: {1}\n", insStackFrame.GetFileName(), insStackFrame.GetFileLineNumber()); } return str; } } }
The first step: Add Log class
Step two: OnConfiguring method to add call log
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(new EFLoggerProvider()); optionsBuilder.UseLoggerFactory(loggerFactory); base.OnConfiguring(optionsBuilder); }