0
votes

I have setup NLog on my project that will save the logging to my audit database (separate from the default database). However, it is failing to write to the database. I have a console logger target as well and that is logging as expected. No errors are shown or given. It merely fails to write to the database.

I have tried various methods provided from google, but none seemed to have worked. I have also tried using NLogBuilder to configure the config for that specific controller but still, it doesn't write to the database

nlog.config file:

<configSections>  
  <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />  
</configSections> 
<nlog internalLogLevel="Trace">
  <targets>
    <target name="ConsoleLogger" type="Console" 
      layout="${longdate}|${level:uppercase=true}|${logger}|${message}"/>
    <target name="DatabaseLog" type="Database">
      <commandtext>
        INSERT INTO Logs 
        (LogDate, LogLevel, Message, Exception) 
        VALUES 
        (@log_date, @log_level, @message, @exception)
      </commandtext>

      <parameter name="@log_date" 
                 layout="${log_date}" 
                 dbType="DateTime"/>
      <parameter name="@thread" 
                 layout="${thread}" 
                 dbType="String"
                 size="255"/>
      <parameter name="@log_level" 
                 layout="${log_level}"
                 dbType="String"
                 size="20" />
      <parameter name="@logger" 
                 layout="${logger}"
                 dbType="String"
                 size="250" />
      <parameter name="@message" 
                 layout="${message}"
                 dbType="String"
                 size="4000" />
      <parameter name="@exception" 
                 layout="${exception}"
                 dbType="String"
                 size="4000" />

      <dbProvider>MySql.Data.MySqlClient.MySqlConnection, MySql.Data</dbProvider>
      <connectionString>User Id=username;Password=password;Host=localhost;Database=audit_database;TreatTinyAsBoolean=false</connectionString>
    </target>
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" maxlevel="Fatal" writeTo="ConsoleLogger,DatabaseLog" />
  </rules>
</nlog>

Controller method:

public static Logger _logger = LogManager.GetCurrentClassLogger(typeof(ActionerController));

_logger.Info("text");

Main.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
      logging.ClearProviders();
      logging.AddNLog();
    }).ConfigureAppConfiguration((hostingContext, config) =>
    {
      config
        .AddJsonFile($"environment-mount/appsettings.json", optional: true)
        .AddEnvironmentVariables();
    }).ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder.UseStartup<Startup>();
    });
1
.NET Core doesn't use app.config files and NLog's config file doesn't need configSections. In fact, this is an invalid XML file because it has two root elements. This example shows what nlog.config should look like - Panagiotis Kanavos
Have you checked Getting Started with ASP.NET Core 3 in NLog's repo? - Panagiotis Kanavos
I went through getting started, I left out the usage of the dependency injected logger. Added that in. Fixed the config as suggested, but it still won't log to the database. It only logs to the console and files. - Luke Holmwood

1 Answers

1
votes

For MySQL, make sure you have installed the MySql.Data package.

There are also some mistakes in your config and code:

  • ${log_date}, ${log_level} and ${thread} don't exist. I guess you mean ${date}, ${level} and ${threadid}. See all options here.
  • LogManager.GetCurrentClassLogger with an argument expects a logger type - so inherits from NLog.Logger. I think you are looking for LogManager.GetCurrentClassLogger() or LogManager.GetLogger(typeof(ActionerController).FullName). See API docs

Of course there could be other errors, e.g. a wrong query, mistyped colum names or wrong column types. NLog could of course tell you the problem:

  • Or enable exceptions. In your config <nlog throwExceptions=true >
  • Or enable the internal log: <nlog internalLogFile="c:\log.txt" internalLogLevel="Warn">. Read more here