Skip to content
This repository has been archived by the owner on Feb 27, 2022. It is now read-only.

Commit

Permalink
Adding an outputTemplate optional parameter to NLog sink
Browse files Browse the repository at this point in the history
  • Loading branch information
Pvlerick committed Nov 14, 2016
1 parent 14352e6 commit fb5f8f4
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 9 deletions.
10 changes: 8 additions & 2 deletions src/Serilog.Sinks.NLog/LoggerConfigurationsNLogExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Serilog.Sinks.NLog;
using Serilog.Configuration;
using Serilog.Events;
using Serilog.Formatting.Display;

namespace Serilog
{
Expand All @@ -24,6 +25,8 @@ namespace Serilog
/// </summary>
public static class LoggerConfigurationsNLogExtensions
{
const string DefaultOutputTemplate = "{Message}";

/// <summary>
/// Adds a sink that writes adapted log events to NLog.
/// </summary>
Expand All @@ -35,14 +38,17 @@ public static class LoggerConfigurationsNLogExtensions
public static LoggerConfiguration NLog(
this LoggerSinkConfiguration loggerConfiguration,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null)
{
if (loggerConfiguration == null)
{
throw new ArgumentNullException("loggerConfiguration");
throw new ArgumentNullException(nameof(loggerConfiguration));
}

return loggerConfiguration.Sink(new NLogSink(formatProvider), restrictedToMinimumLevel);
var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);

return loggerConfiguration.Sink(new NLogSink(formatter), restrictedToMinimumLevel);
}
}
}
16 changes: 11 additions & 5 deletions src/Serilog.Sinks.NLog/Sinks/NLog/NLogSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Formatting;
using System.IO;

namespace Serilog.Sinks.NLog
{
class NLogSink : ILogEventSink
{
readonly IFormatProvider formatProvider;
readonly ITextFormatter textFormatter;

public NLogSink(IFormatProvider formatProvider = null)
public NLogSink(ITextFormatter textFormatter)
{
this.formatProvider = formatProvider;
this.textFormatter = textFormatter;
}

public void Emit(LogEvent logEvent)
Expand All @@ -30,10 +32,14 @@ public void Emit(LogEvent logEvent)
}

var level = GetMappedLevel(logEvent);
var message = logEvent.RenderMessage(formatProvider);

var renderSpace = new StringWriter();
this.textFormatter.Format(logEvent, renderSpace);

//var message = logEvent.RenderMessage(formatProvider);
var exception = logEvent.Exception;

var nlogEvent = new LogEventInfo(level, loggerName, message)
var nlogEvent = new LogEventInfo(level, loggerName, renderSpace.ToString())
{
Exception = exception
};
Expand Down
2 changes: 1 addition & 1 deletion src/Serilog.Sinks.NLog/project.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "3.0.0-*",
"version": "4.0.0-*",
"description": "Serilog event sink that writes to NLog. Merge your new Serilog event stream into your existing NLog infrastructure.",
"authors": [ "Serilog Contributors" ],
"packOptions": {
Expand Down
4 changes: 3 additions & 1 deletion test/Serilog.Sinks.NLog.Tests/Serilog.Sinks.NLog.Tests.xproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>

<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
90 changes: 90 additions & 0 deletions test/Serilog.Sinks.NLog.Tests/Sinks/NLog/NLogSinkTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using NLog;
using NLog.Config;
using NLog.Targets;
using Serilog.Core;
using System.Linq;
using Xunit;

namespace Serilog.Sinks.NLog.Tests.Sinks.NLog
{
public class NLogSinkTest
{
[Fact]
public void LogsAreSentToNLog()
{
// Fixture setup
SetupNLogConfiguration();
// Exercise system
var log = new LoggerConfiguration()
.WriteTo.NLog()
.CreateLogger();
log.Warning("The quick brown fox jumps over the lazy dog");
// Verify outcome
var result = GetLastLoggedLineFromNLogMemotyTarget();
Assert.Equal("Default|Warn|The quick brown fox jumps over the lazy dog", result);
// Teardown
TeardownNLogConfiguration();
}

[Fact]
public void SourceContextIsUsedForNLogLogName()
{
// Fixture setup
SetupNLogConfiguration();
// Exercise system
var log = new LoggerConfiguration()
.Enrich.WithProperty(Constants.SourceContextPropertyName, "Test")
.MinimumLevel.Verbose()
.WriteTo.NLog()
.CreateLogger();
log.Debug("The quick brown fox jumps over the lazy dog");
// Verify outcome
var result = GetLastLoggedLineFromNLogMemotyTarget();
Assert.Equal("Test|Debug|The quick brown fox jumps over the lazy dog", result);
// Teardown
TeardownNLogConfiguration();
}

[Fact]
public void TestOutputTemplate()
{
// Fixture setup
SetupNLogConfiguration();
// Exercise system
var log = new LoggerConfiguration()
.WriteTo.NLog(outputTemplate: "[{Level}] - {Message}")
.CreateLogger();
log.Information("The quick brown fox jumps over the lazy dog");
// Verify outcome
var result = GetLastLoggedLineFromNLogMemotyTarget();
Assert.Equal("Default|Info|[Information] - The quick brown fox jumps over the lazy dog", result);
// Teardown
TeardownNLogConfiguration();
}

private const string MemoryTargetName = "memory";
private const string DefaultNLogLayout = @"${logger}|${level}|${message}";

private void SetupNLogConfiguration()
{
var config = new LoggingConfiguration();
var memoryTarget = new MemoryTarget();
config.AddTarget(MemoryTargetName, memoryTarget);
memoryTarget.Layout = DefaultNLogLayout;
var rule = new LoggingRule("*", LogLevel.Trace, memoryTarget);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
}

private void TeardownNLogConfiguration()
{
LogManager.Configuration = null;
}

private string GetLastLoggedLineFromNLogMemotyTarget()
{
var target = (MemoryTarget)LogManager.Configuration.FindTargetByName(MemoryTargetName);
return target.Logs.Last();
}
}
}
2 changes: 2 additions & 0 deletions test/Serilog.Sinks.NLog.Tests/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"testRunner": "xunit",
"dependencies": {
"xunit": "2.2.0-beta2-build3300",
"xunit.runner.visualstudio": "2.1.0",
"dotnet-test-xunit": "2.2.0-preview2-build1029",
"NLog": "4.4.0-betaV15",
"Serilog.Sinks.NLog": { "target": "project" }
},
"frameworks": {
Expand Down

0 comments on commit fb5f8f4

Please sign in to comment.