NLog 4.6.2 Console Application

For most of our configuration we use the App.config file. If you do not have one, create one and copy a .csproj project’s build configs for handling App.config files or simply start a project with App.config in the visual studio template. Based on .Net framework Console Applications under the .Net 4.7.2 Framework using NLog 4.6.2 however later versions may work just as well.


In the start of the App.config add the following...

<configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <nlog throwExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
          <target name="database" xsi:type="Database" dbProvider="System.Data.SqlClient"
              connectionString="${gdc:item=databaseStr}"
              commandText="INSERT INTO [dbo].[mgReportServerAppLog]  
              ([database_name],[app_name], [version], [message_type], [message], [routine], [src_file], [src_line], [key_field_1], [key_value_1], [username], [computer_name])
              VALUES                                      
              ('300', @app_name, @version, @message_type,  @message, @routine , @src_file, @src_line, @key_field_1, @key_value_1, @username, @computer_name)">
        <parameter name="@app_name" layout="${processname}" />
        <parameter name="@version" layout="${assembly-version}" />
        <parameter name="@message_type" layout="${level}" />
        <parameter name="@message" layout="${message}" />
        <parameter name="@routine" layout="${callsite:className=true:includeSourcePath=true:methodName=true}" />
        <parameter name="@src_file" layout="${currentdir}" />
        <parameter name="@src_line" layout="${callsite-linenumber}" />
        <parameter name="@key_field_1" layout="${event-properties:item=key_field_1 }" />
        <parameter name="@key_value_1" layout="${event-properties:item=key_value_1 }" />
        <parameter name="@username" layout="${environment-user}" />
        <parameter name="@computer_name" layout="${machinename}" />
      </target>
    </targets>
    <rules>
      <logger name="*" writeTo="database" />
    </rules>
  </nlog>


Now via nuget install the Nlog package, you can use the Nuget UI or the following command if you open up the Package Manager Console. For other types of project you mean need more packages however for this setup we are going with the light solution and minimum configuration. 

For now we ignore the other packages based on dotnet or aspnet mvc.  

Install-Package Nlog


Finally we wrap things up in our code using the following example…

namespace ConsoleApplication
{
    using System;
    using NLog;

    public static class Program
    {
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

        public static void Main(string[] args)
        {

            //Change your Database String HERE!
            GlobalDiagnosticsContext.Set("databaseStr","YOURSTR"));
            try
            {
                Logger.Info("Application started...");

                //  run your code here
            }
            catch (Exception e)
            {
                Logger.Fatal(e, "An unexpected exception has occurred");
            }
            finally
            {
                Logger.Info("Application terminated. Press <enter> to exit...");
                Console.ReadLine();
            }
        }
    }
}


Using the example above you can change your database string to whatever you need. If you encounter any sql issues you will receive runtime errors on the first logger reference in your code. 

Using Custom Fields

Before in our App.config we referenced the following

parameter name="@key_field_1" layout="${event-properties:item=key_field_1 }" />
If we want to use this we need to do the following in code for custom fields we are going to pass into the database. Up until now all the fields we set and passed to the database are pre-populated and nothing we need to set other than the string message.


    LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, "", logMessage);
    theEvent.Properties["key_field_1"] = report.ReportConfig.OutputFileName;
    theEvent.Properties["key_value_1"] = reportResult.Runtime.TotalSeconds;
    //DOCS: use of the logger for custom fields
    //        ... and in your App.config file:
    //${event-properties:item=key_field_1 } -- renders key_field_1
    //${event-properties:item=key_field_1 } -- renders key_value_1
    if (logger != null) {
        logger.Log(theEvent);
    }

 

 What we are doing here is assigning our Logger the fields and in our App.config just passing them along to the database. If you don’t set these fields they will be null and will not affect the rest of our logger. You can expand or ignore these fields when & where you like.

Adding File Log and Server Trace Log

<target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />
      <target name="default" xsi:type="File" fileName="logs/app-log.txt" archiveFileName="logs/archives/app-log.{#}.txt" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="7" />  

Starting All Over

For reference you can uninstall your packages via command just as well using the following…

# Uninstalls the Elmah package from the default project
Uninstall-Package Elmah

# Uninstalls the Elmah package and all its unused dependencies
Uninstall-Package Elmah -RemoveDependencies

# Uninstalls the Elmah package even if another package depends on it
Uninstall-Package Elmah -Force

Things Yet to Come!



Additional Notes

Popular posts from this blog

Aspetcore: NLog with Postgresql

Mongodb Cheatsheet

Installing Windows on Acer chromebook 15 cb3-532