Skip to content

Instantly share code, notes, and snippets.

@robbratton
Last active January 5, 2024 17:59
Show Gist options
  • Save robbratton/c8b0d2f5e9088f8dc40aa3ce907eeb06 to your computer and use it in GitHub Desktop.
Save robbratton/c8b0d2f5e9088f8dc40aa3ce907eeb06 to your computer and use it in GitHub Desktop.
NLog Config File and Usage Example

Use NLog with a Custom XML Configuration File in PowerShell

<#
This is an example of how to create an NLog logger in Powershell using a specific configuration file.
#>
# Load the config file.
$ne = New-Object NLog.Config.XmlLoggingConfiguration($ConfigPath)
([NLog.LogManager]::Configuration) = $ne
# Set variables used in the config file.
[NLog.LogManager]::Configuration.Variables['prefix'] = $Prefix
[NLog.LogManager]::Configuration.Variables['directory'] = $LogDirectory
# Get the default logger.
$logger = [NLog.LogManager]::GetCurrentClassLogger()
<?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" throwConfigExceptions="true" throwExceptions="false" internalLogLevel="Warn" internalLogFile="c:\temp\nlog-internal.log">
<!-- See https://github.com/nlog/nlog/wiki/Configuration-file for information on customizing logging rules and outputs. -->
<targets>
<target name="logFile" xsi:type="File" fileName="${var:directory}\${var:prefix}${shortdate}.log" maxArchiveFiles="7" archiveAboveSize="100000000" archiveEvery="Day">
<layout xsi:type="CsvLayout" delimiter="Tab" withHeader="true" quoting="Nothing">
<column name="Timestamp" layout="${date:universalTime=true:format=o}" />
<column name="MachineName" layout="${machinename}" />
<column name="ProcessId" layout="${processId}" />
<column name="ThreadId" layout="${threadID}" />
<column name="Level" layout="${level:upperCase=true}" />
<column name="Message" layout="${message}" />
</layout>
</target>
<!-- <target name="logConsole" xsi:type="ColoredConsole" layout="${level} ${message}" /> -->
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logFile" />
<!-- Common minlevels: Trace, Debug, Info, etc. -->
</rules>
</nlog>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment