clearwaterstream / NLogTarget.Splunk

A simple, battle tested Splunk NLog target that facilitates streaming of log entries to Http Event Collector (HEC)
Apache License 2.0
0 stars 0 forks source link

NLogTarget.Splunk

A simple, lightweight, and extensible Splunk NLog target that facilitates delivery of log entries to Http Event Collector (HEC)

Tested with .NET Framework 4.7.2 and .NET Core 2.1 (in AWS .NET LAMBDA environment as well)

Supports sending log entries in async and sync mode with gzip compression enabled. In async mode, the entries are sent in batches.

Sample NLog.config

The required parameters are

Optional parameters are

Keep in mind that the timestamp must be sent along with the log entries. The library will set the timestamp to the current time (DateTime.UtcNow) so ensure that the time across your servers is synchronized.

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="false"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="C:\logs\nlog_internal.log">
  <extensions>
    <add assembly="NLogTarget.Splunk"/>
  </extensions>
  <targets async="true">
    <target xsi:type="Splunk" name="splunk" endpoint="https://sample.org/services/collector/event" authToken="***" index="sample_index" source="http:your_app">
      <layout xsi:type="JsonLayout" includeAllProperties="true">
        <attribute name="logger" layout="${logger}" />
        <attribute name="severity" layout="${level}" />
        <attribute name="callsite" layout="${callsite:includeSourcePath=false:className=false}" />
        <attribute name="message" layout="${message}" />
        <attribute name="error" layout="${exception:format=ToString}" />
      </layout>
    </target>
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="Splunk" />
  </rules>
</nlog>

NLog_sample.config

Resolving AuthToken Programmatically

It is highly recommended that the AuthToken value is resolved from a secrets vault rather then NLog.config. To resolve the AuthToken programmatically:

Sample AuthToken resolution code

class Program
{
    static readonly Logger logger = LogManager.GetCurrentClassLogger();

    static void Main(string[] args)
    {
        SplunkAuthTokenResolver.OnObtainAuthToken += SplunkAuthTokenResolver_OnObtainAuthToken;

        logger.Info("Testing 123");

        Console.Read();
    }

    static string SplunkAuthTokenResolver_OnObtainAuthToken(string targetName)
    {
        if(targetName == "splunk" || targetName == "splunk_wrapped")
        {
            // get auth token from secrets vault

            return "auth token value";
        }

        return null;
    }
}

- Enjoy Responsibly -