public
Created

Custom NLog Target for sending log events via SMS using Twilio

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
 
namespace Twilio.Targets
{
[NLog.Targets.Target("Sms")]
public class Sms : NLog.Targets.TargetWithLayout
{
[Required]
public string AccountSid { get; set; }
 
[Required]
public string AuthToken { get; set; }
 
[Required]
public string From { get; set; }
 
[Required]
public string To { get; set; }
 
protected override void Write(NLog.LogEventInfo logEvent)
{
string logMessage = this.Layout.Render(logEvent);
 
SendTheMessageToTheRemoteHost(logMessage);
}
 
private void SendTheMessageToTheRemoteHost(string message)
{
string msg = (message.Length > 160) ? message.Substring(0, 160) : message;
 
var client = new TwilioRestClient(this.AccountSid, this.AuthToken);
client.SendSmsMessage(
this.From,
this.To,
msg
);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.