Have you seen our new fluent interface? (3.2.0 feature)
20 Jan 2015With the release of 3.2.0 a new fluent interface has also been introduced. This feature simplifies writing complex logging statements and can be extended with extension methods.
var logger = LogManager.GetCurrentClassLogger();
logger.Info()
.Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
.Property("Test", "InfoWrite")
.Write();
To start with the fluent interface:
- Import the namespace
NLog.Fluent
- Create a
Logger
as regular - Start the fluent interface with
logger.Log(LogLevel...)
,logger.Debug()
,logger.Error()
etc. - Use the fluent interface
- Finish the chain with
.Write()
Full example
using System;
using NLog;
using NLog.Fluent;
class Program
{
void Test()
{
var logger = LogManager.GetCurrentClassLogger();
try
{
//ex 1
logger.Info()
.Property("id", 123)
.Property("category", "test")
.Write();
DoCrash();
}
catch (Exception ex)
{
//ex 2
logger.Log(LogLevel.Error)
.Exception(ex)
.Message("log a message with {0} parameter", 1).Write();
throw;
}
}
private static void DoCrash()
{
//..
}
}