Nlog

Logging To InsightOps via Nlog

To configure your application to log to InsightOps via Nlog, you will need to perform the following tasks:

  • Create a InsightOps account.
  • Create a host and log to receive your log data.
  • Adding the Plugin library and the appropriate InsightOps Appender libraries to your application.
  • Configure the Plugin and the InsightOps appender in your application.
  • Send log messages from your application.
  • These steps are outlined in further detail below.

Setup

The easiest way to add the NLog and the InsightOps Target libraries to your application is to install the logentries.nlog Nuget package. This package will install the InsightOps Target library and will also automatically install the NLog package as a dependency.

Configuring NLog and the InsightOps Appender

General NLog configuration is beyond the scope of this readme. Please refer to the Configuration section of the NLog manual for details on how to configure NLog.

NLog allows log messages to be sent to multiple destinations. In NLog terminology, such an output destination is called a target. Targets must subclass the NLog.Targets.Target class. The InsightOps Plugin library provides such a target component that is specifically designed to send log messages to InsightOps in an efficient manner.

The InsightOps target is configured and added to your NLog configuration in the normal way using a element:

1
<target name="insightops" type="Insight" ... />

The InsightOps target has two categories of settings that are configured somewhat differently:

  • Logging settings
  • InsightOps credentials

NLog Logging Settings

Logging settings determine how the target operates, and are specified as child elements of the element. The InsightOps target supports the following configuration settings:

  • Level: The lowest NLog logging level that should be included. All log messages with a logging level below this level will be filtered out and not sent to InsightOps.
  • Debug: Set to true to send internal debug messages to the Nlog internal logger.
  • UseSsl: Set to true to use SSL to send data to InsightOps (see below for more information).
  • Layout: The layout used to format log messages before they are sent to Logentries.
1
<configSections>
2
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
3
</configSections>
4
<nlog>
5
<extensions>
6
<add assembly="R7Insight.NLog" />
7
</extensions>
8
<targets>
9
<target name="insightops" type="Insight" region="us" debug="true" usessl="false"
10
layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} ${logger} : ${LEVEL}, ${message}"/>
11
</targets>
12
<rules>
13
<logger name="*" minLevel="Debug" appendTo="insightops"/>
14
</rules>
15
</nlog>

NLog InsightOps Credentials

InsightOps credentials determine to which host and log your log messages are sent. The following settings constitute the InsightOps credentials:

Token: The unique token GUID of the log to send messages to. This applies when using the newer token-based logging. AccountKey and Location: The account key and location to send messages to. This applies when using the older HTTP PUT logging (see below for more information). Unlike the logging settings (which are typically configured once for a given application) the InsightOps credentials typically vary based on the environment or instance of your application. For example, your application might run in both a testing and a production environment, and you will most likely wish to have separate logging destinations for those two environments.

Therefore, the InsightOps credentials can be specified more flexibly than the configuration settings. You have three options:

Specify the credentials as child elements of the element (if you don’t need the added flexibility). Specify the credentials as settings in the element in your App.config och Web.config file. Specify the credentials as Windows Azure role configuration settings in your cloud service project (only applicable when running your application as a cloud service in Windows Azure). The InsightOps target uses the CloudConfigurationManager class internally to read the credential values. This class looks for each credential value in the following order:

If the value exists as a Windows Azure role configuration setting, that value is used. Otherwise if the value exists as a setting in the element in your App.config or Web.config file, that value is used. Otherwise if the value exists as a configured child element of the element, that value is used. Here is an example of how to specify the credentials in the element:

1
<target name="insightops" type="Insight" token="bb61600f-f766-451e-b55f-9204f536a79f" ... />

Here is an example of how to specify the credentials in the element in your App.config or Web.config file:

1
<appSettings>
2
<add key="Insight.Token" value="bb61600f-f766-451e-b55f-9204f536a79f" />
3
</appSettings>

Here is an example of how to specify the credentials as Windows Azure role configuration settings:

1
<ServiceConfiguration serviceName="MyApp" osFamily="3" osVersion="*" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" schemaVersion="2013-03.2.0">
2
<Role name="MyRole">
3
<Instances count="2" />
4
<ConfigurationSettings>
5
<Setting name="Insight.Token" value="bb61600f-f766-451e-b55f-9204f536a79f" />
6
</ConfigurationSettings>
7
</Role>
8
</ServiceConfiguration>

Logging Context Information in Web Applications with NLog

In web application it is often helpful to use NLog’s built-in ability to log additional contextual information with each log message. This works particularly well in combination with InsightOps’ log message indexer, which can identify any key-value-pairs in the incoming log message and index those for fast search and retrieval.

Here is an example of how additional web-specific contextual log information can be added to the layout of the InsightOps appender in a format that the InsightOps parser will recognize and index:

1
<target name="logentries" type="Insight"
2
layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} ${logger} ${LEVEL} ${message}${newline}SessionId='${aspnet-sessionid}'; Username='${aspnet-user-identity}'; ${newline}" />

Token-Based Logging

Our recommended method of sending messages to InsightOps is via Token TCP over port 10000. To use this method, select Token TCP as the source type when creating a new log in the InsightOps UI, and then paste the token that is printed beside the log in the value for the Logentries.Token credential setting.

Sending Log Data over SSL/TLS with NLog

The InsightOps appender supports sending log data over SSL/TLS with both of the above logging methods by setting the useSsl logging setting to true in the appender definition. This is more secure but may have a performance impact.

Sending Log Messages from Your Application with NLog

With installation and configuration out of the way, you are ready to send log data to InsightOps.

In each class you wish to log from, add the following using directive at the top if it’s not already there:

1
using NLog;

Then create a logger object at the class level:

private static readonly Logger m_logger = LogManager.getCurrentClassLogger(); This creates a logger with the same name as the current class, which organizes the NLog configuration hierarchy according to your code namespace hierarchy. This provides both clarity when reading the logs, and convenience when configuring different log levels for different areas of your code.

Now within your code in that class, you can log using NLog as normal and it will log to InsightOps.

Examples:

1
loggerLe.Info("This is a test message");
2
loggerLe.Info("This is another test message");
3
String x = System.Console.ReadLine();

Complete code example:

1
using NLog;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
namespace LogentriesLog4NetSampleApp
8
{
9
class Program
10
{
11
private static readonly ILog loggerLe = LogManager.GetLogger( typeof(Program));
12
13
static void Main(string[] args)
14
{
15
loggerLe.Info("This is a test message");
16
loggerLe.Info("This is another test message");
17
String x = System.Console.ReadLine();
18
}
19
}
20
}

Troubleshooting NLog

By default the InsightOps target logs its own debug messages to NLog’s internal logger. Checking these debug messages can help figuring out why logging to InsightOps does not work as expected.

Shutting Down NLog’s Logger

The InsightOps target keeps an internal queue of log messages and communicates with the InsightOps system using a background thread which continuously sends messages from this queue. Because of this, when an application is shutting down, it is possible that some log messages might still remain in the queue and will not have time to be sent to InsightOps before the application domain is shut down.

To work around this potential problem, consider adding the following code to your application, which will block for a moment to allow the InsightOps appender to finish logging all messages in the queue. The AreAllQueuesEmpty() blocks for a specified time and then returns true or false depending on whether the queues had time to become empty before the method returns.

1
public void Application_End()
2
{
3
// This will give LE background thread some time to finish sending messages to InsightOps.
4
var numWaits = 3;
5
while (!LogentriesCore.Net.AsyncLogger.AreAllQueuesEmpty(TimeSpan.FromSeconds(5)) && numWaits > 0)
6
numWaits--;
7
}