Add logging using a .NET trace listener

This topic provides basic examples of how to create a .NET trace listener using Splunk logging for Java.

HTTP Event Collector

The following snippet demonstrates creating a TraceSource object, and then attaching a new HttpEventCollectorTraceListener object as a listener configured to communicate with HTTP Event Collector (EC). Notice the EC-specific port after the hostname, plus the EC token, which has been obtained from the Splunk Enterprise or Splunk Cloud server.

var traceSource = new TraceSource("MyLogger");
traceSource.Switch.Level = SourceLevels.All;
traceSource.Listeners.Clear();
traceSource.Listeners.Add(new HttpEventCollectorTraceListener(
    uri: new Uri("https://splunk-server:8088"),
    token: "205A7CE0-24B6-44CD-9299-333E29BBBCF1");
traceSource.TraceEvent(TraceEventType.Information, "Hello world");

TCP or UDP inputs

The following snippet demonstrates creating a TraceSource object, and then attaching a UdpTraceListener (or TcpTraceListener) object configured to communicate with localhost on port 10000. Then an event is generated, which is sent via UDP (or TCP) to Splunk Enterprise.

// setup
var traceSource = new TraceSource("TestLogger");
traceSource.Switch.Level = SourceLevels.All;
traceSource.Listeners.Clear();
traceSource.Listeners.Add(new UdpTraceListener(IPAddress.Loopback, 10000));
// or, for TCP:
// traceSource.Listeners.Add(new TcpTraceListener(IPAddress.Loopback, 10000));

// log an event
traceSource.TraceEvent(TraceEventType.Information, 1, "Test event");