- 5 minutes to read

Hello World Log Event sample (C#)

This page describes how to create a Visual Studio C# project that creates a Log Event for the purpose of enabling true end to end logging from your custom solutions.

If you want to get started even faster, then download the FileWriterSample that you should use together with the Pickup Service

graph LR roProject(1. Create new Project)-->roNuGet(2. Add NuGet reference) roNuGet --> roCustomCode(3. Set Log Event Properties) roCustomCode --> ro(4. Write Event)

Please review the Asynchronous Logging user guide if you have not already read it.

If you are not a .NET developer then feel free to use any other programming language. The ultimate goal is to produce a JSON based Log Event.

Step 1: Create a new Visual Studio Project

From Visual Studio, create a new Project (we recommend that you create a library so you can reuse the code in a reusable component)
Create New Project
Create New Project

Make sure to select .NET Framework 4.5 or later

Step 2:Add NuGet package reference

Nodinite have multiple libraries/samples available on both github and NuGet. The library to be used in this sample is called Nodinite.Libraries.Contracts.LogRestApi and is available on NuGet:

  1. From within your project add a NuGet reference by right-clicking on the solution and select Manage NuGet Packages...
    Add NuGet package reference

  2. Add a NuGet Reference to Nodinite.Libraries.Contracts.LogRestApi
    Nodinite.Libraries.Contracts.LogRestApi

Click the Install button to add the library to your selected project(s)

If you are using Nodinite, make sure to use the 5.x version or later. If you are using Integration Manager use 4.x version

Step 3: Add custom code

We will now create the Log Event

The Log Event has three distinct parts:

  1. Event details (some mandatory fields)
  2. Payload (optional)
  3. Context properties (optional)
graph TD subgraph "Log Event" subgraph "1. Details" roED[fal:fa-bolt Event Details
LogDateTime = 2018-05-03 13:37:00+02:00
EndPointName = https://api.nodinite.com/...
MessageType=Invoice
...] end subgraph "2. Payload" ro[fal:fa-envelope Message
Body=base64EncodedMessage] end subgraph "3. Context Properties" roKey[fal:fa-key Key Values
InvoiceNo = 123
CorrelationId=456
...] end end

Now in Visual Studio, type LogEvent and add the appropriate using statement by pressing CTRL key followed by the . (dot) key.
![TypeLogEvent][6]

In the top of your .cs file the following using statement should now exist:

using Nodinite.Libraries.Contracts.LogRestApi;

Using Statement for the Log Event.

Create the LogEvent

Now lets create a method that creates and returns the Nodinite LogEvent

private LogEvent CreateNodiniteLogEvent()
{
    return new LogEvent()
    {                
    };
}

Mandatory fields

There are some mandatory fields that you must provide. These are further documented in the JSON Log Event user guide.


// Required values 
LogAgentValueId = 42,
EndPointName = "INT101: Receive Hello World Log Events",
EndPointUri = "C:\\temp\\in",
EndPointDirection = 0,
EndPointTypeId = LogEventEndPointType.File,
OriginalMessageTypeName = "Hello.World.File/1.0",
LogDateTime = DateTime.UtcNow

Optional Fields example

Below is a fully populated Log Event example.

// Required values 
LogAgentValueId = 42,
EndPointName = "INT101: Receive Hello World Log Events",
EndPointUri = "C:\\temp\\in",
EndPointDirection = 0,
EndPointTypeId = LogEventEndPointType.File,
OriginalMessageTypeName = "Hello.World.File/1.0",
LogDateTime = DateTime.UtcNow,

// Optional values
EventDirection = LogEventEventDirection.ExternalIncoming,
ProcessingUser = "DOMAIN\\user",
SequenceNo = 0,
EventNumber = 0,
LogText = "File OK",
ApplicationInterchangeId = "",
LocalInterchangeId = null,
LogStatus = 0,
ProcessName = "My Process",
ProcessingMachineName = "localhost",
ProcessingModuleName = "INT101-HelloWorld-Application",
ProcessingModuleType = "FilePickup",
ServiceInstanceActivityId = null,
ProcessingTime = 80,

// Add Body (payload)
Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { orderid = "123", name = "John Doe" })),

// Add arbitrary Context
Context = new Dictionary<string, string> {
    { "CorrelationId", "064205E2-F7CF-43A6-B514-4B55536C2B67" },
    { DefaultContextProperties.Filename, "Hello.txt" }
}

How do I validate a Log Event?

Below is a sample method that can help you validate your Log Event.

private static void ValidateLogEvent(LogEvent logEvent)
{
    if (!logEvent.IsValid(out List<LogReceiptErrorMessage> errorMessages))
    {
        Console.WriteLine("Log Event is not valid!");
        foreach (var errorMessage in errorMessages)
        {
            Console.WriteLine("{0}\t\t{1}", errorMessage.Title, errorMessage.Message);
        }
    }
    else
    {
        Console.WriteLine("Log Event OK!");
    }
}

Create, Validate and write Log Event to file example

Below is the full example:

using Nodinite.Libraries.Contracts.LogRestApi;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Nodinite.Samples
{
    public class SampleLogEvent
    {
        private LogEvent CreateNodiniteLogEvent()
        {
            return new LogEvent()
            {
                // Required values 
                LogAgentValueId = 42,
                EndPointName = "INT101: Receive Hello World Log Events",
                EndPointUri = "C:\\temp\\in",
                EndPointDirection = 0,
                EndPointTypeId = LogEventEndPointType.File,
                OriginalMessageTypeName = "Hello.World.File/1.0",
                LogDateTime = DateTime.UtcNow,

                // Optional values
                EventDirection = LogEventEventDirection.ExternalIncoming,
                ProcessingUser = "DOMAIN\\user",
                SequenceNo = 0,
                EventNumber = 0,
                LogText = "File OK",
                ApplicationInterchangeId = "",
                LocalInterchangeId = null,
                LogStatus = 0,
                ProcessName = "My Process",
                ProcessingMachineName = "localhost",
                ProcessingModuleName = "INT101-HelloWorld-Application",
                ProcessingModuleType = "FilePickup",
                ServiceInstanceActivityId = null,
                ProcessingTime = 80,

                // Add Body (payload)
                Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { orderid = "123", name = "John Doe" })),

                // Add arbitrary Context
                Context = new Dictionary<string, string> {
                    { "CorrelationId", "064205E2-F7CF-43A6-B514-4B55536C2B67" },
                    { DefaultContextProperties.Filename, "Hello.txt" }
                }

            };
        }

        private void ValidateLogEvent(LogEvent logEvent)
        {
            if (!logEvent.IsValid(out List<LogReceiptErrorMessage> errorMessages))
            {
                Console.WriteLine("Log Event is not valid!");
                foreach (var errorMessage in errorMessages)
                {
                    Console.WriteLine("{0}\t\t{1}", errorMessage.Title, errorMessage.Message);
                }
            }
            else
            {
                Console.WriteLine("Log Event OK!");
            }
        }

        public void CreateValidateAndWriteLogEventToFile()
        {
            LogEvent logEvent = CreateNodiniteLogEvent();
            ValidateLogEvent(logEvent);

            string jsonString = logEvent.ToJson();

            using (StreamWriter file = File.CreateText(string.Format("LogEvent_{0}.json", Guid.NewGuid())))
            {
                file.WriteLine(jsonString);
            }
        }        
    }
}

Make sure to customize the code snippet above according to your log needs. Avoid hard coding and use config file and/or parameters to dynamically set the properties.

The file written in the example above is intended to be consumed by the Pickup Service. Make sure to read more in the Asynchronous Logging user guide.


Next Step