Custom event creation and log this event properties data using NLog

NLog is a .NET library which enables you to add sophisticated tracing code to your application, delivering the functionality in a right manner. It also makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.

Following steps are required for custom event creation and log this event properties data using NLog

1. Creating Log messages: In order to create log messages from the application you need to use the logging API. There are two classes that you will be using the most: Logger and LogManager, both in the NLog namespace. Logger represents the named source of logs and has methods to emit log messages, and LogManager creates and manages instances of loggers.

Logger log = LogManager.GetCurrentClassLogger();

2. Custom event creation:

LogEventInfo objEvent = new LogEventInfo(LogLevel.Info, "", "Info");

3. Event properties creation:

objEvent.Properties["DateTimeValue"] = DateTime.Now.ToString("HH:mm:ss tt");

log.Log(objEvent);

4. Retrieval of custom event properties in NLog.config file:

<target name="file" xsi:type="File" fileName="E:\NLogErrors\ErrorLogFile_${shortdate}_${event-properties:item=Form}.log" layout="

--------------------- ${level}(${event-properties:item=DateTimeValue})${machinename}-------------------- ${newline}

${newline}

${event-properties:item=Value}${newline}">

</target>

Ebook Download
View all
Learn
View all