Share via


Azure Functions : NLog and Database

Here are steps to write NLog to Database in Azure Functions

 

1. via Config (NLog.config)

<?xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="https://www.nlog-project.org/schemas/NLog.xsd"

      xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance">

  <targets>

    <!--<target name="logfile" xsi:type="File" fileName="file.txt" />-->

    <target name="logfile" xsi:type="Database" connectionstring="Server=dbservername.database.windows.net,1433;Initial Catalog=dbname;Persist Security Info=False;User ID=dbuser;Password=password; MultipleActiveResultSets=False; Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;">

      <commandText>

   insert into LogTable(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);

      </commandText>

      <parameter name="@time_stamp" layout="${date}" />

      <parameter name="@level" layout="${level}" />

      <parameter name="@logger" layout="${logger}" />

      <parameter name="@message" layout="${message}" />

    </target>

  </targets>

  <rules>

    <logger name="*" minlevel="Trace" writeTo="logfile" />

  </rules>

</nlog>

2. via Code

static void Main(string[] args)

        {

 

            LogManager.ThrowExceptions = true;

            LogManager.ThrowConfigExceptions = true;

            //InternalLogger.LogToConsole = true;

            InternalLogger.LogFile = "log.txt";

            InternalLogger.LogLevel = LogLevel.Trace;

 

#if DEBUG1 //FILE_TARGET

            NLog.Targets.FileTarget target = new NLog.Targets.FileTarget("file_target");

            target.FileName = "logfile.txt";

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

 

            Logger logger = LogManager.GetLogger("file_target");

#elif DEBUG2

            NLog.Targets.DatabaseTarget target = new NLog.Targets.DatabaseTarget("db_target");

            NLog.Targets.DatabaseParameterInfo param;

 

            //target.DBProvider = "System.Data.SqlClient";

            target.DBHost = "dbservername.database.windows.net";

            target.DBUserName = "dbuser";

            target.DBPassword = "password";

            target.DBDatabase = "dbname";

            target.CommandText = "insert into LogTable(time_stamp,level,logger,message) values(@time_stamp, @level, @logger, @message);";

 

            param = new NLog.Targets.DatabaseParameterInfo();

            param.Name = "@time_stamp";

      param.Layout = "${date}";

            target.Parameters.Add(param);

 

            param = new NLog.Targets.DatabaseParameterInfo();

            param.Name = "@level";

            param.Layout = "${level}";

            target.Parameters.Add(param);

 

            param = new NLog.Targets.DatabaseParameterInfo();

            param.Name = "@logger";

            param.Layout = "${logger}";

            target.Parameters.Add(param);

 

            param = new NLog.Targets.DatabaseParameterInfo();

            param.Name = "@message";

            param.Layout = "${message}";

            target.Parameters.Add(param);

 

 

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            Logger logger = LogManager.GetLogger("db_target");

 

#else

            Logger logger = LogManager.GetCurrentClassLogger();

#endif

   

            logger.Trace("Sample trace message");

            logger.Debug("Sample debug message");

            logger.Info("Sample informational message");

            logger.Warn("Sample warning message");

            logger.Error("Sample error message");

            logger.Fatal("Sample fatal error message");

 

            LogManager.Flush();

        }

3. In Azure Functions, we need to set the location of NLog.config file using XmlLoggingConfiguration() class as shown below:

using System;

using NLog;

using NLog.Common;

using NLog.Config;

 

 

private static Logger logger = null;

 

public static void Run(TimerInfo myTimer, TraceWriter log)

{

 

    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

 

    if (logger == null)

    {

        LogManager.ThrowExceptions = true;

        LogManager.ThrowConfigExceptions = true;

        //InternalLogger.LogToConsole = true;

        InternalLogger.LogFile = "log.txt";

        InternalLogger.LogLevel = LogLevel.Trace;

        LogManager.Configuration = new XmlLoggingConfiguration("D:\\home\\site\\wwwroot\\<your function name>\\NLog.config");

 

        logger = LogManager.GetCurrentClassLogger();

 

    }

4. Also note, we need to add NuGet package details in the Project.json as shown below

image