Skip to content

Commit

Permalink
Added NLog Layout support for WebHookUrl
Browse files Browse the repository at this point in the history
  • Loading branch information
snakefoot committed Nov 13, 2022
1 parent 7241b0d commit 5c7a43e
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions NLog.Slack/SlackTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using NLog.Common;
using NLog.Config;
using NLog.Layouts;
using NLog.Slack.Models;
using NLog.Targets;

Expand All @@ -11,7 +12,7 @@ namespace NLog.Slack
public class SlackTarget : TargetWithContext
{
[RequiredParameter]
public string WebHookUrl { get; set; }
public Layout WebHookUrl { get; set; }

public bool Compact { get; set; }

Expand All @@ -22,13 +23,6 @@ public class SlackTarget : TargetWithContext

protected override void InitializeTarget()
{
if (String.IsNullOrWhiteSpace(this.WebHookUrl))
throw new ArgumentOutOfRangeException("WebHookUrl", "Webhook URL cannot be empty.");

Uri uriResult;
if (!Uri.TryCreate(this.WebHookUrl, UriKind.Absolute, out uriResult))
throw new ArgumentOutOfRangeException("WebHookUrl", "Webhook URL is an invalid URL.");

if (!this.Compact && this.ContextProperties.Count == 0)
{
this.ContextProperties.Add(new TargetPropertyWithContext("Process Name", Layout = "${machinename}\\${processname}"));
Expand All @@ -55,8 +49,12 @@ private void SendToSlack(AsyncLogEventInfo info)
{
var message = RenderLogEvent(Layout, info.LogEvent);

var webHookUrl = RenderLogEvent(WebHookUrl, info.LogEvent);
if (String.IsNullOrWhiteSpace(webHookUrl))
throw new ArgumentOutOfRangeException("WebHookUrl", "Webhook URL cannot be empty.");

var slack = SlackMessageBuilder
.Build(this.WebHookUrl)
.Build(webHookUrl)
.OnError(e => info.Continuation(e))
.WithMessage(message);

Expand Down Expand Up @@ -87,7 +85,7 @@ private void SendToSlack(AsyncLogEventInfo info)
var exceptionAttachment = new Attachment(exception.Message) { Color = color };
exceptionAttachment.Fields.Add(new Field("StackTrace") {
Title = $"Type: {exception.GetType().ToString()}",
Value = exception.StackTrace ?? "N/A"
Value = exception.ToString()
});

slack.AddAttachment(exceptionAttachment);
Expand Down

0 comments on commit 5c7a43e

Please sign in to comment.