I've configured NLog to log errors/logs to two MySQL/Database targets:
<nlog autoReload="false" internalLogFile="omg.txt" throwExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!--<nlog autoReload="false" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-->
<variable name="DefaultLayout" value="${longdate} | ${uppercase:${level}} | ${logger} | ${message}
${exception:innerFormat=ToString:maxInnerExceptionLevel=6:innerExceptionSeparator=InnerException:format=ToString}" />
<targets>
<target xsi:type="ColoredConsole" name="console" layout="${DefaultLayout}" />
<target xsi:type="Null" name="nulltarget" formatMessage="false" layout="${DefaultLayout}" />
<target xsi:type="Database"
name="MySqlErrorTarget"
dbProvider="MySql.Data.MySqlClient" connectionString="x"
keepConnection="true">
<commandText>
CALL Error_Insert(#Message)
</commandText>
<parameter name="#Message" layout="${message}" />
(...)
</target>
<target xsi:type="Database"
name="MySqlLogTarget"
dbProvider="MySql.Data.MySqlClient" connectionString="x"
keepConnection="true">
<commandText>
CALL Log_Insert(#Message)
</commandText>
<parameter name="#Message" layout="${message}" />
(...)
</target>
</targets>
<rules>
<logger name="*" levels="TRACE, DEBUG, INFO" writeTo="MySqlLogTarget"/>
<logger name="*" levels="WARN, ERROR, FATAL" writeTo="MySqlErrorTarget"/>
<logger name="*" minlevel="INFO" writeTo="console" />
</rules>
</nlog>
When MySQL database is available everything works great, however when MySQL goes down, NLog throws StackOverflow exception. Internal log file looks like follows:
2016-03-21 15:36:33.0487 Error Error when writing to database MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts. ---> System.Net.Sockets.SocketException (0x80004005): No such host is known
at System.Net.Dns.GetAddrInfo(String name)
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at MySql.Data.Common.MyNetworkStream.CreateStream(MySqlConnectionStringBuilder settings, Boolean unix)
at MySql.Data.Common.StreamCreator.GetStream(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString)
at NLog.Targets.DatabaseTarget.EnsureConnectionOpen(String connectionString)
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
2016-03-21 15:37:00.1794 Error Error when writing to database MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts. ---> System.Net.Sockets.SocketException (0x80004005): No such host is known
at System.Net.Dns.GetAddrInfo(String name)
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at MySql.Data.Common.MyNetworkStream.CreateStream(MySqlConnectionStringBuilder settings, Boolean unix)
at MySql.Data.Common.StreamCreator.GetStream(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString)
at NLog.Targets.DatabaseTarget.EnsureConnectionOpen(String connectionString)
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
This goes infinitely, thus in the end StackOverflow occurs. Exception reported in Visual Studio looks like follows:
NLog.NLogRuntimeException occurred
HResult=-2146233088
Message=Exception occurred in NLog
Source=NLog
StackTrace:
at NLog.LoggerImpl.<>c__DisplayClass1.<Write>b__0(Exception ex)
at NLog.Internal.SingleCallContinuation.Function(Exception exception)
at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)
at NLog.Targets.Target.WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
at NLog.LoggerImpl.WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
at NLog.Logger.Debug(String message)
at Runner.Main(String[] args) in C:\Repos\x\src\Runner.cs:line 36
InnerException:
ErrorCode=-2147467259
HResult=-2147467259
Message=Unable to connect to any of the specified MySQL hosts.
Number=1042
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString)
at NLog.Targets.DatabaseTarget.EnsureConnectionOpen(String connectionString)
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)
InnerException:
ErrorCode=11001
HResult=-2147467259
Message=No such host is known
NativeErrorCode=11001
Source=System
StackTrace:
at System.Net.Dns.GetAddrInfo(String name)
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at MySql.Data.Common.MyNetworkStream.CreateStream(MySqlConnectionStringBuilder settings, Boolean unix)
at MySql.Data.Common.StreamCreator.GetStream(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.NativeDriver.Open()
InnerException:
I've tried changing the rules to:
<rules>
<logger name="NLog.*" minlevel="TRACE" writeTo="nulltarget" final="true"/>
<logger name="MySql.*" minlevel="TRACE" writeTo="nulltarget" final="true"/>
<logger name="System.*" minlevel="TRACE" writeTo="nulltarget" final="true"/>
<logger name="*" levels="TRACE, DEBUG, INFO" writeTo="MySqlLogTarget"/>
<logger name="*" levels="WARN, ERROR, FATAL" writeTo="MySqlErrorTarget"/>
<logger name="*" minlevel="INFO" writeTo="console" />
</rules>
However, it doesn't help. Any ideas how can I avoid the StackOverflowException?
Set throwExceptions on <nlog to false. The connection exception will be ignored by NLog and NLog won't try to log it to the database.
Turns out that somewhere in my code base was this line invoked:
Trace.Listeners.Add(new NLogTraceListener());
Which caused that error log from MySql was redirected to Trace, and thanks to the NLogTraceListener, it was logged by NLog using MySql target, which failed and was redirected to Trace, and thanks to the NLogTraceListener, it was logged by NLog using MySql target, which... you know how this goes.
I didn't come up with a nice solution since there is no enough info to filter the logs in the TraceListener (just a message as a string). Therefore I've turned off the NLogTraceListener temporarily, as it's not crucial to have it on.
Related
I'm using nlog to trace errors by email - all the configuration is stored in web.config. I'm trying to use appSetting for key enableSsl in nlog mail section but it is not taken into account for this specific key (but it works fine for other keys like: smtpServer, from, to, ...)
The following package are installed:
NLog<br/>
NLog.Extended // required to use appSetting<br/>
Nlog.Targets.Syslog<br/>
Nlog.Web<br/>
Documentation:
Mail-target
AppSetting-Layout-Renderer
Environment is C# .NET
It crashes with: enableSsl="${appsetting:Mail.Ssl.Enabled}"
It works fine with: enableSsl="False"
web.config :
<appSettings>
<add key="Mail.Server" value="mail.myserver" />
<add key="Mail.Server.Port" value="25" />
<add key="Mail.Ssl.Enabled" value="False" />
<add key="Mail.Credentials.User" value="" />
</appSettings>
...
<nlog ..>
<targets>
<target name="mail" xsi:type="Mail" html="true" replaceNewlineWithBrTagInHtml="true" enableSsl="${appsetting:Mail.Ssl.Enabled}" smtpServer="${appsetting:Mail.Server}" from="${appsetting:Mail.From}" to="${appsetting:Mail.To.Error}" subject="Error on my app" layout="${message}..." />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
<!--<logger name="*" minlevel="Info" writeTo="syslog" />-->
<logger name="*" minlevel="Error" writeTo="mailBuffer" />
<logger name="*" minlevel="Info" writeTo="database" />
</rules>
</nlog>
nlog-internal.log :
Error when setting '${appsetting:Mail.Ssl.Enabled}' on attibute
'enableSsl' Exception: NLog.NLogConfigurationException: Error when
setting property 'EnableSsl' on Mail Target[mail] --->
System.FormatException: ${appsetting:Mail.Ssl.Enabled} is not a valid
value for Boolean. ---> System.FormatException: String was not
recognized as a valid Boolean.
at System.Boolean.Parse(String value)
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext
context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext
context, CultureInfo culture, Object value)
at NLog.Internal.PropertyHelper.TryTypeConverterConversion(Type type, String value, Object& newValue)
at NLog.Internal.PropertyHelper.SetPropertyFromString(Object obj, String propertyName, String value, ConfigurationItemFactory
configurationItemFactory)
--- End of inner exception stack trace ---
at NLog.Internal.PropertyHelper.SetPropertyFromString(Object obj, String propertyName, String value, ConfigurationItemFactory
configurationItemFactory)
at NLog.Config.LoggingConfigurationParser.ConfigureObjectFromAttributes(Object
targetObject, ILoggingConfigurationElement element, Boolean
ignoreType)
enableSsl isn't of type Layout, but of type boolean. (see docs).
This means it isn't layoutable and so you can't use layout renderers for this value.
You could (as exception) variables in the config, as those are inlined when reading the config. e.g.
<variable name="myvar" value="true" />
...
<target name="mail" xsi:type="Mail" enableSsl="${myvar}" ../>
If you need to change the config dynamically, you need some code.
I had this working, but I tried to update nlog and use the nuget packages, including NLog.Windows.Forms.
Now I am getting NLog.NLogConfigurationException with the inner exception:
Target cannot be found: 'RichTextBox'
The project references both: NLog and NLog.Windows.Forms
from packages.config:
<package id="NLog" version="4.3.4" targetFramework="net46" />
<package id="NLog.Config" version="4.3.4" targetFramework="net46" />
<package id="NLog.Schema" version="4.3.4" targetFramework="net46" />
<package id="NLog.Windows.Forms" version="4.2.3" targetFramework="net46" />
from nlog.config
<target name="rtb" xsi:type="RichTextBox" controlName="RichTextBox1" formName="NewForm"
useDefaultRowColoringRules="true" layout="[${date}] [${level:uppercase=true}] [${logger}] ${message}" />
...
<logger name="*" minlevel="Trace" writeTo="file,rtb" />
Adding internal logging didn't seem to give much more information:
...
...
2016-06-03 06:17:23.9385 Trace Scanning MessageLayoutRenderer 'Layout Renderer: ${message}'
2016-06-03 06:17:23.9550 Info Adding target File Target[file]
2016-06-03 06:17:23.9550 Debug Registering target file: NLog.Targets.FileTarget
2016-06-03 06:17:23.9550 Error Error in Parsing Configuration File. Exception: NLog.NLogConfigurationException: Exception occurred when loading configuration from C:\Users\Derek.Morin\Documents\Visual Studio 2010\Projects\ScriptCode\ScriptCode.ConvertedToC#\bin\x86\Debug\NLog.config ---> System.ArgumentException: Target cannot be found: 'RichTextBox'
at NLog.Config.Factory`2.CreateInstance(String name)
at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
--- End of inner exception stack trace ---
2016-06-03 06:17:23.9700 Error Error has been raised. Exception: System.ArgumentException: Target cannot be found: 'RichTextBox'
at NLog.Config.Factory`2.CreateInstance(String name)
at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
If I can't get an answer for how to get it working with the nlog.config file, at least I found the following workaround:
I adapted the answer from here: ( I didn't like the colouring choices )
Display NLog trace in RichTextBox
private void SetupRichTextBoxLogger()
{
NLog.Windows.Forms.RichTextBoxTarget target = new NLog.Windows.Forms.RichTextBoxTarget();
target.Name = "RichTextBox";
target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
target.ControlName = nameof(this.RichTextBox1);
target.FormName = nameof(NewForm);
target.AutoScroll = true;
target.MaxLines = 0;
target.UseDefaultRowColoringRules = true;
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "AsyncRichTextBox";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging( asyncWrapper, LogLevel.Trace );
}
Besides having the nuget-package NLog.Windows.Forms installed (Remember to use v4.6 or newer, together with NLog 5.0)
Then it is also recommended to update NLog.config to include NLog.Windows.Forms-assembly in <extensions>:
<?xml version="1.0" encoding="utf-8" ?>
<nlog>
<extensions>
<add assembly="NLog.Windows.Forms"/>
</extensions>
...
</nlog>
FWIW, I had this problem after upgrading to NLog 5 and removing the deprecated NLog.Config. Upon reverting to 4.7.15 with NLog.Config, the problem no longer occurred.
In my case, having NLog.Windows.Forms installed did not help.
I have NLog 4.2.3 configured to write to a database and a text file using the following config:
<?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" autoReload="true" internalLogLevel="Error" internalLogFile="C:/tmp/NLog.txt">
<targets>
<target name="database" xsi:type="Database" dbProvider="Npgsql.NpgsqlFactory,Npgsql,Version=2.0.12.00,Culture=neutral,PublicKeyToken=5d8b90d52f46fda7" connectionString="Server=xxx.xxx.xxx.xxx;Port=5432;User Id=userid;Password=password;Database=testdb;">
<commandText>INSERT INTO invoice_log (message, level, logger) VALUES (#msg, #level, #logger)</commandText>
<parameter name="#msg" layout="${message}" />
<parameter name="#level" layout="${level}" />
<parameter name="#logger" layout="${logger}" />
</target>
<target name="log" xsi:type="File" layout="${longdate} | ${logger} | ${level:uppercase=true}: ${message}" fileName="${basedir}/Logs.txt" keepFileOpen="false" encoding="iso-8859-2" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="database" />
<logger name="*" minlevel="Trace" writeTo="log" />
</rules>
</nlog>
I'm trying to log a simple Info message. It logs correctly to the text file, but it fails for the database and I get the following error in the NLog internal log file:
Error Error when writing to database System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString)
at NLog.Targets.DatabaseTarget.EnsureConnectionOpen(String connectionString)
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
I have looked at configs from other similar questions (NLog is not writing to database table, NLog to PostgreSQL connection), but I can't see what is missing from mine?
According to the nlog docs, dbProvider is an invariant name for a factory registered in a config file OR the fully qualified name of a type that implements IDbConnection. Npgsql.NpgsqlConnection implements the required interface and has a parameterless contructor. NpgsqlFactory does not and it does not have a parameterless constructor (the cause of the error).
I'm trying to setup NLog to send mail and use my system settings (with a pickup directory) as documented here
Here's my NLog configuration
<nlog internalLogLevel="Trace" internalLogFile="C:\NLogInternal.log" throwExceptions="true" autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="c:\backupservice.log.txt" layout="${longdate} ${callsite} ${level} ${message}"/>
<target name="console" xsi:type="Console" />
<target xsi:type="EventLog"
name="event"
layout="${longdate} ${callsite} ${level} ${message}"
source="BackupService"
eventId="898"
log="BackupService"
/>
<target xsi:type="Mail"
name="email"
useSystemNetMailSettings="True"
layout="${longdate} ${callsite} ${level} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Fatal" writeTo="email" />
<logger name="*" minLevel="Info" writeTo="event" />
<logger name="*" minLevel="Debug" writeTo="console" />
</rules>
Here is my mail setting:
<system.net>
<mailSettings>
<smtp from="backup#[COMPANY].com" deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\testmail\Pickup" />
<network host="mail.[COMPANY].com" password="[PASSWORD]" userName="[EMAIL_ADDRESS]" />
</smtp>
</mailSettings>
Here is the output from NLog's internal logging:
** SNIP **
2013-06-20 17:41:03.8368 Debug Setting 'MailTarget.name' to 'email'
2013-06-20 17:41:03.8368 Debug Setting 'MailTarget.useSystemNetMailSettings' to 'True'
2013-06-20 17:41:03.8688 Error Error System.NotSupportedException: Parameter useSystemNetMailSettings not supported on MailTarget
at NLog.Internal.PropertyHelper.SetPropertyFromString(Object o, String name, String value, ConfigurationItemFactory configurationItemFactory)
at NLog.Config.XmlLoggingConfiguration.ConfigureObjectFromAttributes(Object targetObject, NLogXmlElement element, Boolean ignoreType)
at NLog.Config.XmlLoggingConfiguration.ParseTargetElement(Target target, NLogXmlElement targetElement)
at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String baseDirectory)
at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String baseDirectory)
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)...
2013-06-20 17:41:03.8688 Error ConfigSectionHandler error: NLog.NLogConfigurationException: Exception occurred when loading configuration from C:\Projects\Fee\WindowsServices\BackupService\BackupService\bin\Debug\BackupService.vshost.exe.Config ---> System.NotSupportedException: Parameter useSystemNetMailSettings not supported on MailTarget
at NLog.Internal.PropertyHelper.SetPropertyFromString(Object o, String name, String value, ConfigurationItemFactory configurationItemFactory)
at NLog.Config.XmlLoggingConfiguration.ConfigureObjectFromAttributes(Object targetObject, NLogXmlElement element, Boolean ignoreType)
at NLog.Config.XmlLoggingConfiguration.ParseTargetElement(Target target, NLogXmlElement targetElement)
at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String baseDirectory)
at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String baseDirectory)
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
--- End of inner exception stack trace ---
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
at NLog.Config.XmlLoggingConfiguration..ctor(XmlElement element, String fileName)
at NLog.Config.ConfigSectionHandler.System.Configuration.IConfigurationSectionHandler.Create(Object parent, Object configContext, XmlNode section)
I'm not sure what I'm doing wrong or if it's a bug in Nlog.
NB: I've tried both useSystemNetMailSettings and UseSystemNetMailSettings.
So I didn't get NLog to work specifically through NLog but I used a work around. NLog has a "MethodCall" target that I used like so:
<target name="sendmail" xsi:type="MethodCall" className="BackupLib.Email, BackupLib" methodName="Send">
<parameter layout="backupservice#[COMPANY].com" />
<parameter layout="backups#[COMPANY].com" />
<parameter layout="FATAL ERROR: Backup Service on ${machinename}" />
<parameter layout="${longdate} - ${callsite} - ${message}" />
</target>
</targets>
<rules>
<logger name="*" minLevel="Fatal" writeTo="sendmail" />
<logger name="*" minLevel="Info" writeTo="event" />
<logger name="*" minLevel="Debug" writeTo="console" />
</rules>
This allowed me to call a static method (BackupLib.Email.Send()) that sent out an email for me. Simple yet effective and since I used the SMTPClient baked into .NET it used my system email settings!
Glad I finally got this.
If you have the extension NLog.MailKit installed and you try to use the useSystemNetMailSettings parameter within your target, this will causes the error Parameter useSystemNetMailSettings not supported on MailTarget.
Uninstalling the NLog.MailKit package fixed this for me!
The Nlog.MailKit package is only required if you are using NetStandard1.X.
I'm using NLog to log to network. From my understanding, the code and configuration outlined below should always work, no matter other parts of the project. And it indeed works fine for some configurations of my project, but for others it fails, and I can't really figure out the exact reason.
I noticed that (in a non-working configuration) NLog throws when logging to 127.0.0.2 but fails silently (no error in log, but apparently no message is sent) for 127.0.0.1. Since both addresses ought to behave identically I'm left stumped. I'm using Sentinel as log viewer.
How is it possible that NLog fails despite having the exact same code and configuration, and how come it behaves differently for 127.0.0.1 and .2?
Code:
internal class Program
{
protected static Logger logger = LogManager.GetLogger ("Console.Main");
private static void Main (string[] args)
{
logger.Trace ("Initializing platform");
NLog.config:
<targets>
<target name="viewer"
xsi:type="NLogViewer"
address="udp://127.0.0.2:9999"/>
<target name="file"
xsi:type="File"
layout="${longdate} ${logger} ${message} ${exception}"
fileName="${basedir}/logs/logfile.txt"
keepFileOpen="false"
encoding="iso-8859-2" />
<target xsi:type="ColoredConsole"
layout="${logger} ${message} ${exception}"
name="console"/>
</targets>
<rules>
<logger name="*"
minlevel="Trace"
writeTo="viewer" />
<logger name="*"
minlevel="Trace"
writeTo="file" />
<logger name="*"
minlevel="Info"
writeTo="console" />
</rules>
Internal logfile for 127.0.0.2:
2011-10-11 12:05:08.4364 Error Target exception: System.Net.Sockets.SocketException (0x80004005): No such host is known
at System.Net.Dns.InternalGetHostByAddress(IPAddress address, Boolean includeIPv6)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at NLog.Internal.NetworkSenders.UdpNetworkSender..ctor(String url)
at NLog.Internal.NetworkSenders.NetworkSender.Create(String url)
at NLog.Targets.NetworkTarget.NetworkSend(String address, Byte[] bytes)
at NLog.Targets.NetworkTarget.Write(LogEventInfo logEvent)
at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
Found it. All configurations were referencing the same DLL, but some of them used one from GAC instead of the one hinted at. Manually copying the DLLs and rewriting project references fixed the issue.
Why doesn't VS give a highest level warning on missing DLLs ...