Nlog
Logging To Log Management (InsightOps) via Nlog
To configure your application to log to Log Management (InsightOps) via Nlog, you will need to perform the following tasks:
- Create a Log Management (InsightOps) account.
- Create a host and log to receive your log data.
- Adding the Plugin library and the appropriate Log Management (InsightOps) Appender libraries to your application.
- Configure the Plugin and the Log Management (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 Log Management (InsightOps) Target libraries to your application is to install the logentries.nlog Nuget package . This package will install the Log Management (InsightOps) Target library and will also automatically install the NLog package as a dependency.
Configuring NLog and the Log Management (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 Log Management (InsightOps) Plugin library provides such a target component that is specifically designed to send log messages to Log Management (InsightOps) in an efficient manner.
The Log Management (InsightOps) target is configured and added to your NLog configuration in the normal way using a element:
<target name="insightops" type="Insight" ... />
The Log Management (InsightOps) target has two categories of settings that are configured somewhat differently:
- Logging settings
- Log Management (InsightOps) credentials
NLog Logging Settings
Logging settings determine how the target operates, and are specified as child elements of the <target>
element. The Log Management (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 Log Management (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 Log Management (InsightOps) (see below for more information).
- Layout: The layout used to format log messages before they are sent to Logentries.
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog>
<extensions>
<add assembly="R7Insight.NLog" />
</extensions>
<targets>
<target name="insightops" type="Insight" region="us" debug="true" usessl="false"
layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} ${logger} : ${LEVEL}, ${message}"/>
</targets>
<rules>
<logger name="*" minLevel="Debug" appendTo="insightops"/>
</rules>
</nlog>
NLog Log Management (InsightOps) Credentials
Log Management (InsightOps) credentials determine to which host and log your log messages are sent. The following settings constitute the Log Management (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 Log Management (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 Log Management (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 <appSettings>
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 Log Management (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 <appSettings>
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:
<target name="insightops" type="Insight" token="bb61600f-f766-451e-b55f-9204f536a79f" ... />
Here is an example of how to specify the credentials in the <appSettings>
element in your App.config
or Web.config file:
<appSettings>
<add key="Insight.Token" value="bb61600f-f766-451e-b55f-9204f536a79f" />
</appSettings>
Here is an example of how to specify the credentials as Windows Azure role configuration settings:
<ServiceConfiguration serviceName="MyApp" osFamily="3" osVersion="*" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" schemaVersion="2013-03.2.0">
<Role name="MyRole">
<Instances count="2" />
<ConfigurationSettings>
<Setting name="Insight.Token" value="bb61600f-f766-451e-b55f-9204f536a79f" />
</ConfigurationSettings>
</Role>
</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 Log Management (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 Log Management (InsightOps) appender in a format that the Log Management (InsightOps) parser will recognize and index:
<target name="logentries" type="Insight"
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 Log Management (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 Log Management (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 Log Management (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 Log Management (InsightOps).
In each class you wish to log from, add the following using directive at the top if it’s not already there:
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 Log Management (InsightOps).
Examples:
loggerLe.Info("This is a test message");
loggerLe.Info("This is another test message");
String x = System.Console.ReadLine();
Complete code example:
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogentriesLog4NetSampleApp
{
class Program
{
private static readonly ILog loggerLe = LogManager.GetLogger( typeof(Program));
static void Main(string[] args)
{
loggerLe.Info("This is a test message");
loggerLe.Info("This is another test message");
String x = System.Console.ReadLine();
}
}
}
Troubleshooting NLog
By default the Log Management (InsightOps) target logs its own debug messages to NLog’s internal logger. Checking these debug messages can help figuring out why logging to Log Management (InsightOps) does not work as expected.
Shutting Down NLog’s Logger
The Log Management (InsightOps) target keeps an internal queue of log messages and communicates with the Log Management (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 Log Management (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 Log Management (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.
public void Application_End()
{
// This will give LE background thread some time to finish sending messages to Log Management (InsightOps).
var numWaits = 3;
while (!LogentriesCore.Net.AsyncLogger.AreAllQueuesEmpty(TimeSpan.FromSeconds(5)) && numWaits > 0)
numWaits--;
}