Categories
Database Development

Want to log Database connection failure issue in other file using NLog

I am working on .Net Core 2.2 and MySQL.
General log of application are logged into Database using NLog but I want to log only DB errors (If occurs while logging) to the file.

How I can capture DB connection failure to the file with custom fields like UserID.?

Here’s the code of NLog.config:

<?xml version="1.0" encoding="utf-8" ?>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  throwExceptions="false"
  internalLogLevel="Warn"
  internalLogFile="D:\logs\New\internal-nlog.txt">
<targets>
<target name="database" xsi:type="Database"
          dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" 
connectionString="${var:myConnectionstring}">

 <commandText>
    insert into log (
     Logged,  Message,
     CallSite, Exception, userID
    ) values (
     @Logged, @Message,
     @Callsite, @Exception, @userID
    );
  </commandText>

  <parameter name="@logged" layout="${date}" />
  <parameter name="@message" layout="${message}" />
  <parameter name="@callSite" layout="${event-properties:Callsite}" />
  <parameter name="@exception" layout="${exception:tostring}" />
  <parameter name="@userID" layout="${event-properties:userID}" />
</target>
</targets>
<rules>
<logger name="*" level="Error" writeTo="database" />

</rules>
</nlog>

In .Net core I had written this:

Logger logger = LogManager.GetCurrentClassLogger();
                LogManager.Configuration.Variables["myConnectionstring"] 
=Setting.connString;
                LogManager.ReconfigExistingLoggers();

                logger.SetProperty("userID", "UR0001");
                logger.SetProperty("Callsite", ex.Error.TargetSite.Name);

                logger.LogException(NLog.LogLevel.Error, ex.Error.Message,ex.Error);

Leave a Reply

Your email address will not be published. Required fields are marked *