Introduction
I recently created a NLog target extension to write log message to Microsoft Teams Channel.
NLog Targets for Microsoft Teams
Sending log messages to Microsoft Teams Channel is a good way to notify the development team or the service desk team if there is anything happened in your application. It helps proactively find out the issues sooner.
Below are some benefits to send log message to MS Teams
- Log message shows up in Teams instantly
- All team members get notified
- Log messages are searchable with Teams
Let's Code
First, let's create a console app using Visual Studio. I named the project as NLogTeams, and targeting .NET 6.
Then we need to install the necessary NuGet package. Just right click on the Solution and click on Manage NuGet Packages for Solution.
Type in NLog.Targets.MicrosoftTeams
in the search box, and install it. All the depended packages will be installed to the project as well.
Now let's add a new xml file to the project, and name this new file as nlog.config.
Open up the nlog.config
file, copy & paste the code below and save.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="internal.log"
internalLogLevel="Off" >
<!-- the targets to write to -->
<targets>
<!-- write logs to Microsoft Teams -->
<target xsi:type="MicrosoftTeams, NLog.Targets.MicrosoftTeams"
name="msTeams"
WebhookUrl="Put your Teams Webhook URL here"
ApplicationName="Your Application Name"
CardTitle="Title - ${level:uppercase=true}: ${date} - [${logger}]"
layout="[${level:uppercase=true}] ${logger} - ${message} ${all-event-properties}"
/>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minlevel="Trace" writeTo="msTeams" />
</rules>
</nlog>
You need to get the MS Teams Channel webhook URL. Please follow the Microsoft's instruction to create the incoming webhook in Teams.
Once you have the webhook URL, all you need to do is paste it into the nlog.config
file.
And make sure the nlog.config
file is always Copy to Output Directory
Finally, you can now send log message to your Teams Channel. Let's test it by replacing the code in the Program.cs
with the code below.
using NLog;
MyClass.TestMethod();
public class MyClass
{
static ILogger _logger = LogManager.GetCurrentClassLogger();
public static void TestMethod()
{
Console.WriteLine("Hello World!");
_logger.Info("Log to MS Teams channel like a boss");
}
}
That's it. And the result would be like this.
Conclusion
Many businesses are leveraging Microsoft Teams for collaboration. I hope this helps you to integrate your application with Microsoft Teams to receive Error notification easily.
Top comments (0)