As much as I have enjoyed working with log4net in the psat NLog works much more seamlessly for .NET apps (it has good, solid abstractions)
From Nuget Package Manager, you can find and reference NLog and the accompanying NLog.Config which simplifies setup. To configure NLog logging, simply point the required properties (you need at least a logFile variable, a target and a rule to get started) to your desired values in the config file that NLog.Config creates in your project root (NLog.config):
Configuration:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<variable name="logFilePath" value="C:\NLog\IDG.log" />
<targets>
<target name="logfile"
xsi:type="File"
fileName="${logFilePath}"
layout="${longdate} LEVEL=${level:upperCase=true}: ${message}"
keepFileOpen="true" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Warn" writeTo="logFile"/>
</rules>
</nlog>
This example uses a log file target in C:\NLog directory; you can utilize a wide variety of logging targets to broadcast app errors
Source Code:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NLog;
namespace ExtRSTests
{
[TestClass]
public class NLogTests
{
private static Logger logger = LogManager.GetCurrentClassLogger();
[TestMethod]
public void TestLoggerToFile()
{
logger.Warn("Something in the app happened that may indicate trouble ahead....");
logger.Error("Uh-oh. Something broke.");
}
}
}
With the logging levels, log formatting (timestamps) and abundant integration options, NLog is a complete logging solution
With NLogger you can implement logging for an array of targets including file, email, database and 3rd party integrations (ie. send message to Slack channel if logger generates any "Error" or "Fatal" level log message).
Reference: https://www.infoworld.com/article/3144535/how-to-work-with-nlog-in-net.html
No comments:
Post a Comment