Logging Sql queries in log file using EF core and Log4net

.net-core c# entity-framework-core log4net

Question

I'm trying to log SQL queries into a file using log4net and .NET Core (EF 3.1).

I tried the following configuration:

Startup.cs

loggerFactory.AddLog4Net();

DBContext.s

private readonly ILoggerFactory _loggerFactory;

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

                    optionsBuilder.UseLoggerFactory(_loggerFactory);

        }

log4netConfig:

 <appender name="logger" type="log4net.Appender.RollingFileAppender">
    <file value="c:\\log.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maximumFileSize value="100MB" />
    <maxSizeRollBackups value="3"/>
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="[%thread] ; %date ; %property{ExcutionTime} ; %message%newline" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="DEBUG" />
      <levelMax value="DEBUG" />
    </filter>
  </appender>

I got an empty file as a result. What am I missing?

1
1
3/9/2020 2:04:16 PM

Popular Answer

You can try the following within your DbContext class:

private readonly ILogging _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MyContext(): base("<connectionstring>")
{
    Database.Log = log => _logger.Debug(log);
}

There is already a quite similar answer that might help you further. Take a look at the following:How to log SQL generated by EF using log4net

0
3/9/2020 1:00:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow