Quantcast
Channel: NLog
Viewing all 75 articles
Browse latest View live

We are working on 3.2.1

$
0
0

To fix some small issues (submitted on GitHub - thanks), we are working on 3.2.1. This release will contain two bugfixes:

  • The stacktrace was broken under specific conditions. This was introduced with the “skip assembly” feature.
  • The LogManager.Configuration.Variables property wasn’t implemented in the correct class.

Full details are available on GitHub.


NLog 4.0 - Roadmap and release date

$
0
0

With the upcoming release of 4.0, we’re doing some things differently: we are time-boxing the release and so the release date is now already known: June 2nd, 2015, a year after the release of 3.0!

Issues for 4.0 are now prioritized with the MoSCoW method. In short this means:

  • We will label the issues with Must have, Should have, Could have and Wont have this time around
  • The release will be postponed if not all must haves are implemented.
  • We will release even if not all should haves are implemented.
  • Could haves would be nice, but only if we have enough time, according to the planned release date.

The roadmap of 4.0:

Please note that “pull requests” (PR’s), if accepted a week before release, are also released with 4.0!

I would also like to emphasize that NLog is a fully open source project. So also the roadmap and internal discussions are open. If you’re interested in the NLog process and discussions, just look at the discussions at the Github issues list

NLog 3.2.1 has been released

$
0
0

NLog 3.2.1 has been released yesterday. The release contains the following bug fixes:

  • The default timeout on the SMTP target could lead to connection issues. This has been resolved.
  • The stack trace renderer was broken since 3.2.0 with the addition of the blacklist assembly feature. Both are working correctly now.
  • In 3.2.0 ‘Programmatic access to variables defined in configuration file’ was featured. Unfortunately, the posted example was not working. It’s now possible to access the variables with the use of LogManager.Configuration.Variables.

Unit tests have been added for the above issues to prevent regression bugs. Details of the bug fixes can be seen on the GitHub milestone

Last, but certainly not least: thanks for reporting these issues!

NLog 4.0 release candidate is online

$
0
0

The release candidate of NLog 4.0 is online. More than 100 issues are closed in GitHub. The release candidate can be downloaded from NuGet.

First of all, thanks for the reported issues and requested features!

Features

This release contains the following features:

Zipped file archives

The FileTarget can now compress the archived files to zip format. Example: set EnableArchiveFileCompression in config file:

<targetname="file"xsi:type="File"layout="${longdate} ${logger} ${message}"fileName="${basedir}/logs/logfile.txt"archiveFileName="${basedir}/archives/log.{#}.txt"archiveEvery="Day"archiveNumbering="Rolling"maxArchiveFiles="7"enableArchiveFileCompression="true"/>

Logging exceptions (breaking change)

Logging of exceptions is now more consistent and complete than before. This is a breaking change. All the logger methods, such as .Debug, Error etc. now contains a first optional parameter of the type Exception. Only this parameter would be written as Exception to the log and can be used in the layout renderer, for example ` ${exception:format=tostring}`.

Changes:

  • All “exception” methods starts with Exception parameter. E.g. Error(Exception exception, string message, params object[] args).
  • All “exception” methods have a ‘args’ as parameter for formatting the message.
  • All “exception” methods have an overload with an IFormatProvider as parameter.

Changes that are not backwards-compatible. * removed “exceptionCandidate” hack: Log(string message, Exception ex) would write to exception property instead of message. This is non-backwards compatible in behaviour! * all other “exception methods”: Eg. ErrorException and Error(string message, Exception exception) are marked as Obsolete, also in the interfaces.

//NLog 4.0Logger.Error(ex,"ow noos");Logger.Error(ex,"ow noo {0}","s");//ObsoleteLogger.ErrorException(ex,"ow noos");//BREAKING CHANGE: no compile error, but exception is used in message formatting.Logger.Error("ow noos",ex);//don't do this.//consistent with:Logger.Error("ow noos {0}",var1");

Conditional logging

In extreme cases logging could affect the performance of your application. There is a small overhead when writing a lot of log messages, like Tracing. In this case it’s now possible to only include the Trace and Debug call with a debug release. Instead of:

Logger.Trace("entering method {0}",methodname);

Use:

Logger.ConditionalTrace("entering method {0}",methodname);

This call will be removed by the .Net compiler if the DEBUG conditional compilation symbol is not set – default on a release build.

Auto load extensions

Assemblies with the name “NLog*.dll”, like “NLog.CustomTarget.dll” are now loaded automatically. This assembly should be in the same folder as NLog.dll. Of course you can load NLog extensions manually with the <Extensions> config

AllEventProperties layout renderer

A new layout renderer which outputs all of the event’s properties. Format and separator can be manually configured. Usage examples:

  • ${all-event-properties}
  • ${all-event-properties:Separator=|}
  • ${all-event-properties:Separator= | :Format=[key] is [value]}

This combines nicely with the fluent interface introduced in 3.2.0.

Examples:

varlogger=LogManager.GetCurrentClassLogger();logger.Info().Message("This is a test fluent message '{0}'.",DateTime.Now.Ticks).Property("Test","InfoWrite").Property("coolness","200%").Property("a","not b").Write();
  • In case of ${all-event-properties} this would produce: Test=InfoWrite, coolness=200%, a=not b
  • In case of ${all-event-properties:Format=[key] is [value]} this would produce: Test is InfoWrite, coolness is 200%, a is not b

Writing to JSON

A new layout that renders log events as structured JSON documents. Example:

<targetname="jsonFile"xsi:type="File"fileName="${logFileNamePrefix}.json"><layoutxsi:type="JsonLayout"><attributename="time"layout="${longdate}"/><attributename="level"layout="${level:upperCase=true}"/><attributename="message"layout="${message}"/></layout></target>

would write: { "time": "2010-01-01 12:34:56.0000", "level": "ERROR", "message": "hello, world" }

LoggingRule final behavior (breaking change)

The behavior of the final attribute has been changed. Example:

<loggername="logger1"level="Debug"final=true/>

Before 4.0 it would mark all messages from the logger “logger1” as final. In 4.0 it will only mark the debug messages as final.

Added Eventlog.EntryType

When writing to the Eventlogger, NLog would writes to Information, Warning or Error entrytype, depending on the level. This is now configurable (with layout renderes) and offers the opportunity to write also a FailureAudit or SuccessAudit and/or use it with conditions.

Other

  • The EventLogTarget.Source now accepts layout-renderers. Note: layout renderers can not be used when in- or uninstalling the target.
  • The Console- and ColorConsole target has an encoding property.
  • The application domain layout renderer has been added. Examples: ${appdomain}, ${appdomain:format=short} or ${appdomain:format=long}.
  • Added CallSiteLineNumber layout renderer. usage: ${callsite-linenumber}
  • Added SkipFrames option to the Stacktrace layout renderer
  • The WebserviceTarget has the option IncludeBOM. Possible options:
    • null: doesn’t change BOM.
    • true: always include UTF-8 BOM UTF-8 encodings.
    • false: default, always skip BOM on UTF-8 encodings.
  • FileTarget uses time from the current TimeSource for date-based archiving.
  • Multicast with the LogReceiverTarget is now possible
  • The Mailtarget has less required parameters (at least To, CC or BCC should be set) and the Mailtarget logs their errors correctly to the internal logger now.
  • The Counter.Sequence now accepts layout renderers.

Bug fixes

Over 30 bugs has been solved. The full list can be viewed on Github.

The most noticeable bugs:

  • The default value of DatabaseTarget.CommandType could lead to exceptions
  • If the XML was broken (invalid), auto reload would be disabled - the application needed a restart before reading the changed configuration.
  • The Logmanager.GetCurrentClassLogger was not thread-safe and with many concurrent calls it would throw an exception.
  • Various fixes to the archiving of files.
  • Bugfix: WebserviceTarget wrote encoded UTF-8 preamble.

Breaking changes

NLog 4.0 has some breaking changes. To sum up:

  • LoggingRule.Final behaviour has been changed.
  • The methods of logging exception data has been changed.
  • The webservice target won’t write a BOM with UTF-8 (default, can be set)
  • All properties that have been changed to accept layout renderers.

Wiki

Please note that the wiki hasn’t been updated yet.

Feedback

Any feedback or issues to report? Please post them in this GitHub issue or create a new issue.

NLog 4.0 has been released.

$
0
0

NLog 4.0 has been released! More than 100 issues are closed in GitHub. The release can be downloaded from NuGet.

We had a small delay (less than a week) on releasing this version. We underestimated the need for a release candidate and the time needed for documenting a changes on the wiki .

Thanks again for the reported issues and requested features!

This post is almost identical to the release candidatie news post

Features

This release contains the following features:

Zipped file archives (.Net 4.5 and higher)

The FileTarget can now compress the archived files to zip format. Example: set EnableArchiveFileCompression in config file:

<targetname="file"xsi:type="File"layout="${longdate} ${logger} ${message}"fileName="${basedir}/logs/logfile.txt"archiveFileName="${basedir}/archives/log.{#}.txt"archiveEvery="Day"archiveNumbering="Rolling"maxArchiveFiles="7"enableArchiveFileCompression="true"/>

Because we use the standard stuff of .Net for this, it’s only available in .Net 4.5 and higher.

Consistent logging of exceptions (breaking change)

Logging of exceptions is now more consistent and complete than before. This is a breaking change. All the logger methods, such as .Debug, Error etc. now contains a first optional parameter of the type Exception. Only this parameter would be written as Exception to the log and can be used in the layout renderer, for example ` ${exception:format=tostring}`.

Changes:

  • All “exception” methods starts with Exception parameter. E.g. Error(Exception exception, string message, params object[] args).
  • All “exception” methods have a ‘args’ as parameter for formatting the message.
  • All “exception” methods have an overload with an IFormatProvider as parameter.

Changes that are not backwards-compatible. * removed “exceptionCandidate” hack: Log(string message, Exception ex) would write to exception property instead of message. This is non-backwards compatible in behaviour! * all other “exception methods”: Eg. ErrorException and Error(string message, Exception exception) are marked as Obsolete, also in the interfaces.

//NLog 4.0Logger.Error(ex,"ow noos");Logger.Error(ex,"ow noo {0}","s");//ObsoleteLogger.ErrorException(ex,"ow noos");//BREAKING CHANGE: no compile error, but exception is used in message formatting.Logger.Error("ow noos",ex);//don't do this.//consistent with:Logger.Error("ow noos {0}",var1");

Conditional logging

In extreme cases logging could affect the performance of your application. There is a small overhead when writing a lot of log messages, like Tracing. In this case it’s now possible to only include the Trace and Debug call with a debug release. Instead of:

Logger.Trace("entering method {0}",methodname);

Use:

Logger.ConditionalTrace("entering method {0}",methodname);

This call will be removed by the .Net compiler if the DEBUG conditional compilation symbol is not set – default on a release build.

Auto load extensions

Assemblies with the name “NLog*.dll”, like “NLog.CustomTarget.dll” are now loaded automatically. This assembly should be in the same folder as NLog.dll. Of course you can load NLog extensions manually with the <Extensions> config

AllEventProperties layout renderer

A new layout renderer which outputs all of the event’s properties. Format and separator can be manually configured. Usage examples:

  • ${all-event-properties}
  • ${all-event-properties:Separator=|}
  • ${all-event-properties:Separator= | :Format=[key] is [value]}

This combines nicely with the fluent interface introduced in 3.2.0.

Examples:

varlogger=LogManager.GetCurrentClassLogger();logger.Info().Message("This is a test fluent message '{0}'.",DateTime.Now.Ticks).Property("Test","InfoWrite").Property("coolness","200%").Property("a","not b").Write();
  • In case of ${all-event-properties} this would produce: Test=InfoWrite, coolness=200%, a=not b
  • In case of ${all-event-properties:Format=[key] is [value]} this would produce: Test is InfoWrite, coolness is 200%, a is not b

Writing to JSON

A new layout that renders log events as structured JSON documents. Example:

<targetname="jsonFile"xsi:type="File"fileName="${logFileNamePrefix}.json"><layoutxsi:type="JsonLayout"><attributename="time"layout="${longdate}"/><attributename="level"layout="${level:upperCase=true}"/><attributename="message"layout="${message}"/></layout></target>

would write: { "time": "2010-01-01 12:34:56.0000", "level": "ERROR", "message": "hello, world" }

Notes:

  • Currently the layout will always create an non-nested object with properties.
  • Also there is no way to prevent escaping of the values (e.g. writing custom JSON as value)
  • The JSON will be written on one line, so no newlines.

Improved loggingRule final behavior (breaking change)

The behavior of the final attribute has been changed. Example:

<loggername="logger1"level="Debug"final=true/>

Before 4.0 it would mark all messages from the logger “logger1” as final. In 4.0 it will only mark the debug messages as final.

Added Eventlog.EntryType

When writing to the Eventlogger, NLog would writes to Information, Warning or Error entrytype, depending on the level. This is now configurable (with layout renderes) and offers the opportunity to write also a FailureAudit or SuccessAudit and/or use it with conditions.

Other

  • The EventLogTarget.Source now accepts layout-renderers. Note: layout renderers can not be used when in- or uninstalling the target.
  • The Console- and ColorConsole target has an encoding property.
  • The application domain layout renderer has been added. Examples: ${appdomain}, ${appdomain:format=short} or ${appdomain:format=long}.
  • Added CallSiteLineNumber layout renderer. usage: ${callsite-linenumber}
  • Added SkipFrames option to the Stacktrace layout renderer
  • The WebserviceTarget has the option IncludeBOM. Possible options:
    • null: doesn’t change BOM.
    • true: always include UTF-8 BOM UTF-8 encodings.
    • false: default, always skip BOM on UTF-8 encodings.
  • FileTarget uses time from the current TimeSource for date-based archiving.
  • Multicast with the LogReceiverTarget is now possible
  • The Mailtarget has less required parameters (at least To, CC or BCC should be set) and the Mailtarget logs their errors correctly to the internal logger now.
  • The Counter.Sequence now accepts layout renderers.

Bug fixes

Over 30 bugs has been solved. The full list can be viewed on Github.

The most noticeable bugs:

  • The default value of DatabaseTarget.CommandType could lead to exceptions
  • If the XML was broken (invalid), auto reload would be disabled - the application needed a restart before reading the changed configuration.
  • The Logmanager.GetCurrentClassLogger was not thread-safe and with many concurrent calls it would throw an exception.
  • Various fixes to the archiving of files.
  • Bugfix: WebserviceTarget wrote encoded UTF-8 preamble.

Breaking changes

NLog 4.0 has some breaking changes. To sum up:

  • LoggingRule.Final behaviour has been changed.
  • The methods of logging exception data has been changed.
  • The webservice target won’t write a BOM with UTF-8 (default, can be set)
  • All properties that have been changed to accept layout renderers.

NLog.Extended, NLog.Web and NLog.Windows.Forms

$
0
0

With the release of NLog 4.0 we have split the package NLog.Extended to NLog.Web and NLog.Windows.Forms. This will give us the opportunity to clean up the references in NLog.Extended. There are also some targets and layout renderers still in NLog.Extended, we will also create new packages for those in the future.

For now this this will results in:

  • NLog.Web package contains the targets and layout-renderes specific to ASP.Net and IIS. Version 2.0 is compatible with NLog 4.0
  • NLog.Windows.Forms package contains targets specific for Windows.Forms. Version 2.0 is compatible with NLog 4.0
  • All other are in NLog.Extended package - This is for currently only the MSMQ target and ${appsetting} layout renderer. Version 4.0 is compatible with NLog 4.0
  • Please note: the classic ASP (so non-ASP.Net) are still in the NLog package

This wasn’t communicated in the initial NLog 4.0 release post - which could lead to upgrade issues - we are sorry for that.

Wiki updated

The wiki has been updated to make more clear which Targets and which Layout Renderers are in each package.

Source code and issues

The new extension packages, NLog.Web and NLog.Windows.Forms have their own GitHub reposities. Please post questions, feature requests or bug reports to the related repository.

Auto load

Because we introduced auto load of extentions in NLog 4.0 (see news post), there is no need for additional configuration. Just install NLog.Web, NLog.Windows.Forms and/or NLog.Extended with Nuget.

NLog 4.0.1 has been released.

$
0
0

We just released a patch release for 4.0. This release fixes the following problems:

  • The auto-load of the extensions was not working in combination with ASP.NET.
  • Autoflush was not optimal implemented.
  • We reverted an unneeded breaking change in MailTarget. The SMTP property is not required anymore. This is consistent with 3.x.
  • Loading the NLog assembly from an embedded resource is now working.
  • Writing to files could lead to OverflowExceptions in 64-bit runtime. This was a bug since NLog 2.0.
  • Some descriptions for the obsolete methods are corrected.

Thanks for reporting those issues and creating Pull Requests! Without your help we could not release of 4.0.1 on short time.

PS: details of the fixed issues can be found on the GitHub 4.0.1 milestone.

Extending NLog is... easy!

$
0
0

Not everyone knows NLog is easy to extend to your own wishes. There can be various reasons for wanting to extend NLog. For example when you want to write your log messages to a custom output or you would like to use your own ${} macros.

With some attributes you can create your own custom target, layout or layout renderer with ease. Also creating your own conditions for filter messages is possible!

I will describe creating your own layout renderer and custom target in this post.

How to write a custom layout renderer?

Create a class which inherits from NLog.LayoutRenderers.LayoutRenderer, set the [LayoutRenderer("your-name"] on the class and override the Append(StringBuilder builder, LogEventInfo logEvent) method. Invoke in this method builder.Append(..) to render your custom layout renderer.

Example

We create a ${hello-universe} layout renderer, which renders… “hello universe!”.

[LayoutRenderer("hello-universe")]publicclassHelloUniverseLayoutRenderer:LayoutRenderer{protectedoverridevoidAppend(StringBuilderbuilder,LogEventInfologEvent){builder.Append("hello universe!");}}

How to pass configuration options to the layout render?

Just create public properties on the layout renderer. The properties can be decorated with the [RequiredParameter] and [DefaultParameter] attributes. With the [RequiredParameter] attribute, NLog checks if this property has a value and throws an exception when it hasn’t. The property names are required in your config by default. The property name of the first value can be skipped, if the property is decorated with the [DefaultParameter] attribute - see the examples below.

It’s not required for the property to be a string. NLog takes care of the appropriate conversions when necessary. You can use, inter alia, the following types for the properties: integer, string, datetime and boolean.

For example:

[LayoutRenderer("hello-universe")]publicclassHelloUniverseLayoutRenderer:LayoutRenderer{/// <summary>/// I'm not required/// </summary>publicstringConfig1{get;set;}/// <summary>/// I'm required! /// </summary>        [RequiredParameter]publicstringConfig2{get;set;}/// <summary>/// Hi! I'm the default parameter. You can also set me as required./// </summary>        [DefaultParameter]publicboolCaps{get;set;}

Example usages:

  • ${hello-universe} - Raises exception: required parameter “Config2” isn’t set.
  • ${hello-universe:Config2=abc} - OK, “Config2” property set.
  • ${hello-universe:true:config2=abc} - Default parameter “Caps” set to true.
  • ${hello-universe:true:config2=abc:config1=yes} - All the three properties set.

How to write a custom target?

Creating a custom target is almost identical to creating a custom layout renderer.

The created class should now inherit from NLog.Targets.TargetWithLayout and override the Write() method. In the body of the method invoke this.Layout.Render() to render the message text.

Example

An example of a custom target:

[Target("MyFirst")]publicsealedclassMyFirstTarget:TargetWithLayout{publicMyFirstTarget(){this.Host="localhost";}    [RequiredParameter]publicstringHost{get;set;}protectedoverridevoidWrite(LogEventInfologEvent){stringlogMessage=this.Layout.Render(logEvent);SendTheMessageToRemoteHost(this.Host,logMessage);}privatevoidSendTheMessageToRemoteHost(stringhost,stringmessage){// TODO - write me }}

How to pass configuration options to the target?

The property “host” is a configurable option to this target. You can pass the value as attribute in the config: <layout type="myFirst" host="test.com" />

How to use the custom target or layout renderer

First put your custom target or layout renderer in a separate assembly (.dll). Then you should register your assembly. Starting from NLog 4.0, assemblies with the name “NLog*.dll”, such as “NLog.CustomTarget.dll” are now registered automatically - they should be in the same folder as “NLog.dll”.

If that’s not the case you should register your assembly manually: reference your assembly from the the config file using the <extensions /> clause. Only the assembly name is needed (without “.dll”).

Configuration file example:

<nlog><extensions><addassembly="MyAssembly"/></extensions><targets><targetname="a1"type="MyFirst"host="localhost"/><targetname="f1"type="file"layout="${longdate} ${hello-universe}"fileName="${basedir}/logs/logfile.log"/></targets><rules><loggername="*"minLevel="Info"appendTo="a1"/><loggername="*"minLevel="Info"appendTo="f1"/></rules></nlog>

Do I really need to create a separate assembly?

Not really. You should then register your target programmatically. Just make sure to register your stuff at the very beginning of your program, before any log messages are written.

staticvoidMain(string[]args){//layout rendererConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("hello-universe",typeof(MyNamespace.HelloUniverseLayoutRenderer));//targetConfigurationItemFactory.Default.Targets.RegisterDefinition("MyFirst",typeof(MyNamespace.MyFirstTarget));// start logging here }

NLog is Looking for Developers!

$
0
0

This year the NLog project has grown a lot:

  • We have released more often (and NLog 4.1 is on its way)
  • We have redesigned and improved the website (nlog-project.org)
  • The process of giving support and handling issues has been improved
  • A lot of old issues are fixed/closed.
  • The website is fully up-to-date, the wiki has been expanded and old forums have been closed.
  • Twitter and Gitter have been set up.

However, we want to grow even more. We’d like to:

  • Release even more often
  • Fix more bugs
  • Add more features
  • Improve the support for other platforms like Mono, PCL, Xamarin
  • Improve the automatic release management
  • Measure, and improve, the code coverage of the unit tests.

Currently the NLog team consists of two people. If we want to develop NLog further, we need more horsepower! And so we are looking for developers!

If you are interested in contributing to one of the most popular .Net libraries –we are ranked in the top 100 of NuGet, and when excluding the non-.Net and Microsoft packages, we rank in the top 10.– then get in touch with us on Gitter or Github :)

Get in touch with us on Gitter or Github :)

NLog 4.1 is Now Available!

$
0
0

A new version of NLog has been released!

We fixed around 25 bugs, added some new features and made the migration of NLog 3 to 4 easier. The release can be downloaded from NuGet.

Check for all the details the GitHub 4.1 milestone.

Features

This release contains the following features:

Overhaul variables

Since 4.0 you can read the variables defined in the configuration file. We also claimed you could change the values, but we were wrong… The variables where implemented like a kind of macros and changing them would not give the expected results.

In NLog 4.1, we created a new method to render the variables, which fits a lot better in the NLog library: we created a layout renderer for the variables! With the same syntax you can define the variables, but rendering is a bit different.

In NLog 4.0 you would define:

<nlog><variablename='user'value='admin'/><variablename='password'value='realgoodpassword'/><targets><targetname='debug'type='Debug'layout='${message} and ${user}=${password}'/></targets><rules><loggername='*'minlevel='Debug'writeTo='debug'/></rules></nlog>

In 4.1 you can use the $var{} layout renderer:

<nlog><variablename='user'value='admin'/><variablename='password'value='realgoodpassword'/><targets><targetname='debug'type='Debug'layout='${message} and ${var:user}=${var:password}'/></targets><rules><loggername='*'minlevel='Debug'writeTo='debug'/></rules></nlog>

What’s the real advantage here?

  • It is in line with NLog’s current code
  • Variables can be changed, deleted and created from the API
  • A default value can be configured for a variable, e.g. ${var:password:default=unknown}
  • The old variables can still be used and so this is completely backwards-compatible.

You might wonder: why has the old method not been replaced? The answer is simple: the new method only works on Layout types and not on plain strings.

Object values for GDC, MDC and NDC contexts

The context classes, GCD, MCD and NDC, now support using object values instead of strings. This is mostly beneficial from the API perspective.

The get method still returns a string - for backwards-compatibility reasons. We created a new method: getObject.

When writing to the logs, the object is converted to a string

GlobalDiagnosticsContext.Set("myDataBase","someValue");//already possibleGlobalDiagnosticsContext.Set("myDataBaseNumber",2);//4.1+

Easier upgrade from NLog 3 to NLog 4

With the release of NLog 4.0 we made some breaking changes. Those breaking changes made upgrading an issue: all the code has to be upgraded to NLog 4 at once.

The main cause was the change of behavior of Log(string message, Exception ex). This call should be replaced by Log(Exception ex, string message) in NLog 4.0.

Changing all those calls can be difficult at once. So we have introduced the following option:

<nlogexceptionLoggingOldStyle='true'>

With this option enabled, you can still use Log(string message, Exception ex) in NLog 4.

So the upgrade path to NLog 4

  1. Enable “exceptionLoggingOldStyle” in the configuration
  2. Upgrade to NLog 4.1+
  3. (this can take some time): replace the calls to Log(string message, Exception ex) etc.
  4. Disable “exceptionLoggingOldStyle” in the configuration

Note: we will remove this feature in NLog 5.0

New JSON options

New options have been added for writing JSON output.

  • More control over spaces: SuppressSpaces. Example:
<layoutxsi:type="JsonLayout"SuppressSpaces="false"><attributename="process_name"layout="${processname}"/><attributename="short_message"layout="${message}"/></layout>
  • The JSON encoding can be disabled for properties.
<layoutxsi:type="JsonLayout"><attributename="Message"layout="${message}"encode="false"/></layout>

Example call:

logger.Info("{ \"hello\" : \"world\" }");

See the wiki

Integrated NLog.Contrib to core

The NLog.Contrib code has been integrated with the core of NLog. The following features are now available on the NLog package:

  • Mapped Diagnostics Context (MDLC): Async version of Mapped Diagnostics Context Allows for maintaining state across asynchronous tasks and call contexts.
  • The Mapped Diagnostics Context Layout renderer: ${mdlc}
  • Trace Activity Id Layout Renderer: ${activityid} write the System.Diagnostics his trace correlation id.

All events layout renderer: optional writing of caller information

The all events layout renderer introduced in NLog 4.0 was unexpectedly writing caller information, like current method etc, to the targets. This is now an option and disabled by default.

For example:

  • ${all-event-properties} writes “Test=InfoWrite, coolness=200%, a=not b”
  • ${all-event-properties:includeCallerInformation=true} writes “Test=InfoWrite, coolness=200%, a=not b, CallerMemberName=foo, CallerFilePath=c:/test/log.cs, CallerLineNumber=1001”

Call site line number layout renderer

Officially introduced in NLog 4.0, but was not available due to a merge fault. The ${callsite-linenumber} writes the line number of the caller.

Easy replacement of newlines

With the ${replace} layout renderer it was already possible to replace the newlines, but it was a bit tricky to use - different systems, different newlines.

The ${replace-newlines} layout renderer fixes this.

WCF Log Receiver Changes

4.0.0 introduced an unattended breaking changing that replaced the WcfLogReceiverClient with the WcfLogReceiverClientFacade (NLog/NLog#783). It was not only a naming issue, but also some functionality was lost and there was a lot of code duplication.

Unfortunately, there was not an easy fix, so the following was done to try to make it less of a breaking change. The changes are still breaking, but minus a recompilation, the changes should be mostly transparent. See NLog/NLog#874 for all of the changes related to WCF Log Receiver.

Changes from 3.2.1

Compared to 3.2.x, these the changes:

  • Use ILogReceiverTwoWayClient instead of ILogReceiverClient. ILogReceiverClient is still in the code, but is marked obsolete.
  • If your code is dependent on ClientBase, then change it to WcfLogReceiverClientBase

Changes from 4.0.0

Compared to 4.0.x, these the changes:

  • The return type for the method CreateWcfLogReceiverClient() in LogReceiverWebServiceTarget is WcfLogReceiverClient again, but is marked obsolete.
  • Use CreateLogReceiver(), which returns IWcfLogReceiverClient to reduce breaking changes in the future.

Event properties - culture and format options

The event properties are object values. When writing them with ${event-properties} to the logs, the values are converted to strings. It’s now possible to control the culture and format.

Examples: ${event-properties:prop1:format=yyyy-M-dd} and ${event-properties:aaa:culture=nl-NL}

Bugs

Various bugs are fixed in this version. The most notable ones:

UNC path issues

4.0.1 did gave issues with configuration files or binaries hosted on UNC locations.

Fixes in file archiving

Multiple bugs are fixed with file archiving:

  • Archive files where sometimes deleted in the wrong order.
  • DeleteOldDateArchive could delete files not being actual archives. #847

Fixed Mono build

This release finally builds again on Mono! We are busy adding Travis CI integration to keep the Mono build working.

Exception is not correctly logged when calling without message

Writing an exception as only argument to a logger, like logger.Info(new Exception()) was not correctly registering the exception to the log messages.

Internal logger improvements

Some small improved has been made to the internal logger.

NLog 4.1.1 has been released!

$
0
0

We just released a new version of NLog which fixes a few issues in NLog 4.1.0.

Features

  • MDLC now also supports objects, such as MDC, GDC and NDC (those were added in 4.1.0)

Bug fixes:

  • NLog won’t crash if there are binaries starting with “nlog” that we can’t load (those were loaded by the auto load feature)
  • Directory was required with the internal logger
  • Fixed assembly name issue with strong name. With the release of NLog 4.1.0 we made a mistake with the full name. We changed the version in it to 4.1.0.0, but because of the strong naming, we should keep it 4.0.0.0. This the curse of strong naming, and at least in NLog 4 we should just accept it.

In the NLog 4.1.1, the full name is the same as NLog 4.0.0 and 4.0.1.

If nuget is adding the following to your (main) .config:

<dependentAssembly><assemblyIdentityname="NLog"publicKeyToken="5120e14c03d0593c"culture="neutral"/><bindingRedirectoldVersion="0.0.0.0-4.1.0.0"newVersion="4.1.0.0"/></dependentAssembly>

You should remove it, or change it to:

<dependentAssembly><assemblyIdentityname="NLog"publicKeyToken="5120e14c03d0593c"culture="neutral"/><bindingRedirectoldVersion="0.0.0.0-4.1.0.0"newVersion="4.0.0.0"/></dependentAssembly>
  • If you use other libraries built on NLog 3, 4.1.0 or before: change it
  • If you don’t use other libraries built on NLog, or those which are built on NLog 4.x (expected 4.1.0), remove it

We are sorry if the upgrade to 4.1.0 caused any issues. We are aware that the strong naming sometimes gives more issues than solving things and that versioning issues with strong naming are common. But some users need the strong name, and therefore we will keep it for at least version 4.

Other:

  • Obsolete text fixed
  • Removed some unused classes (moved to NLog.Windows.Forms before)

Download it from nuget!

How can we improve NLog? We have now UserEcho!

$
0
0

Do you have a feature request or another idea how we can improve NLog?

We are now also on UserEcho, so vote or add ideas!

Happy coding, Julian

PS: if you like to have more status updates, just follow us on Twitter.

NLog 4.2 is here!

$
0
0

NLog 4.2 has been released. This release contains some small features and (important) bug fixes.

We take semver serious, so all changes are backwards-compatible.

Features

  • Performance Counter Target: it’s now possible to configure the step size for the counter target. Before the step size was always one.
  • Mail Target: pickupDirectoryLocation and deliveryMethod are configurable from the NLog config.
  • Cached Layout Renderer: a clearCache option has been added for more control over clearing the cache. See wiki.
  • File target: auto add .zip to compressed archive when archiveName isn’t specified.

Bug fixes

Inner layout can now contain colons

An inner layout can now contain colons, but it needs an escape.

It is required to escape : and } in an inner layout because:

  • : because it’s a value separator. ${when:when=1 == 1:Inner=Test\: Hello}
  • } because it can be the end of another layout renderer when double nested. ${rot13:inner=${rot13:inner=${when:when=1 == 1:Inner=Test \} Hello}}}

Other bugfixes

  • Colored Console Target: highlight whole words was broken.
  • Mail Target: when useSystemNetMailSettings was false, some settings were still used from the <mailSettings> of the .Net config.
  • Removed unnecessary System.Drawing references for Xamarin.
  • File Target: sometimes an exception was thrown when archiving was enabled.
  • File Target: file archiving DateAndSequence & FileArchivePeriod.Day won’t always work.
  • GetTargetsByLevelForLogger could throw a “Collection was modified” exception.

No bug nor feature

Improved document and error messages regarding the ‘type’ argument of Getcurrentclasslogger and GetLogger. Please keep in mind:

  • It should inherit from Logger.
  • Instead of creating an instance of Logger, it will create an instance of loggerType.
  • type argument necessary when using custom Loggers. Most of the time it isn’t required to pass a type to those methods.

We improved other docs and internal logging in the code. Our code coverage has also been increased.

Thanks

The NLog team has expanded greatly! We’d like to thank all the collaborators who have made this release possible:

Happy coding!

Julian (@304NotModified)

NLog 4.2.1 has been released!

$
0
0

Release notes:

  • Show warning for Databasetarget.UseTransactions instead of exception.
  • NetworkTarget: improved performance, allow configuring of max connections. See wiki.
  • Filetarget: Max archives settings sometimes removes to many files.
  • Prevent Collection was modified (ObjectGraphScanner.ScanProperties)
  • General memory pressure improvements.
  • LogReceiverWebServiceTarget.CreateLogReceiver() should be virtual
  • VariableLayoutRenderer does not work with Custom LogManagers.

NLog.Windows.Forms 4.2 has been released!

$
0
0

NLog.Windows.Forms 4.2 has been released including a new feature for the RichTextBoxTarget— it is now possible to add clickable links to log messages.

Features

This release contains the following features:

It is now possible to add clickable links to messages show in in the RichTextBox control and receive whole event info in the link click handler. To do this, set target’s newly introduced supportLink parameter to true and use new ${rtb-link} layout renderer to specify link part of the layout. To receive link click events, add a handler to RichTextBoxTarget.LinkClicked event. Use RichTextBoxTarget.GetTargetByControl(RichTextBox control) static method to access the target attached to a specific RichTextBox control.

Not sure how to use it? Here are few examples.

Exception details example

When logging exceptions to RichTextBoxTarget you have to find a compromise between flooding the control with huge stacktraces and missing important information. Not anymore! Now you may long only a short description into textbox, and show whole details when user clicks a link:

Just setup a proper layout (don’t forget to enable supportLinks)

<targetxsi:type="RichTextBox"layout="${message}${onexception:inner= ${exception:format=Message} ${rtb-link:details}}"....supportLinks="true"..../>

And add a link click handler:

publicForm1(){InitializeComponent();RichTextBoxTarget.ReInitializeAllTextboxes(this);//more on this laterRichTextBoxTarget.GetTargetByControl(richTextBox1).LinkClicked+=Form1_LinkClicked;}privatevoidForm1_LinkClicked(RichTextBoxTargetsender,stringlinkText,LogEventInfoevent){MessageBox.Show(event.Exception.ToString(),"Exception details",MessageBoxButtons.OK);}

Focusing at specific item example

Sometimes you may need to not only notify user of some problem (like validation failing), but also help him navigate to the problematic item (for example when the list is huge). In this case you may store item’s id of some sort in the LogEventInfo.Property, turn it into a link and navigate to the item in link click handler:

The layout:

<targetxsi:type="RichTextBox"layout="${message} ${rtb-link:${event-properties:item=Index}}"....supportLinks="true"..../>

Validation code:

privatevoidvalidateButton_Click(objectsender,EventArgse){logger.Info("Validation started");foreach(ListViewItemiteminlistView1.Items){if(item.SubItems[1].Text.Contains("bad")){logger.Info().Message("Validation failed on line").Property("Index",(int)item.Tag).Write();return;}}logger.Info("Validation succeeded");}

Event handling code:

publicForm2(){InitializeComponent();RichTextBoxTarget.ReInitializeAllTextboxes(this);RichTextBoxTarget.GetTargetByControl(richTextBox1).LinkClicked+=Form2_LinkClicked;}privatevoidForm2_LinkClicked(RichTextBoxTargetsender,stringlinkText,LogEventInfoevent){intlineIndex=(int)event.Properties["Index"];listView1.EnsureVisible(lineIndex);listView1.SelectedIndices.Add(lineIndex);listView1.Select();}

Hope you could find more useful applications of this new feature!

A note on 4.1 release

In case you are not sure whatRichTextBoxTarget.ReInitializeAllTextboxes(this)call does, then you might have missed a feature added in 4.1 release. It improves the RichTextBoxTarget functional by allowing it to be configured and initialized before the actual control is created. CheckallowAccessoryFormCreationandmessageRetentionoptions description in the target’s documentation


NLog 4.3 RC is Now Available!

$
0
0

update 27 march: RC 2 is now online which resolves a bug in finding the correct stackframe in for ${callsite} etc. This was broken since 4.3-beta 1.


NLog 4.3 is almost ready. There are some changes in the core, so therefore a Release Candidate (RC) has been released. Right now there are 132 closed issues in NLog 4.3, which makes NLog 4.3 the largest release since years. We have had a lot of contributions from the community (thanks!) and have you noticed that NLog has more main contributors than before?

The release can be downloaded from NuGet.

Check for all the details the GitHub 4.3 milestone.

Please note that currently not all the docs have been updated yet.

Features

This release contains the following features:

Support Windows Phone 8, Xamarin Android and Xamarin iOS (beta)

In NLog 4.3 support has been added for the following platforms: Windows Phone 8, Xamarin Android and Xamarin iOS. The support is still in beta as we didn’t get the unit tests running.

Not every feature is working on those platforms, for example auto reloading the configuration is not supported in Xamarin. A full overview of what is supported on each platform can be viewed on the wiki.

Consistent handling of exceptions (BEHAVIOUR CHANGE)

The logging and throwing of exceptions was previously inconsistent. Not all of it was logged to the internal logger and some times they got lost. For example, the async wrapper (or async attribute) was catching all exceptions without a proper rethrow.

This is bad as it is sometimes unclear why NLog isn’t working (got it myself multiple times). This has been fixed in NLog 4.3!

  • All exceptions are logged to the internal logger
  • The “throwExceptions” option will be respected in all cases

Advise: disable throwExceptions in production environments! (this the default)

<nlogthrowConfigExceptions="false">

Control of exception throwing for configuration errors

The following is stated in multiple locations: > By default exceptions are not thrown under any circumstances.

This was not true for configuration errors - those were always rethrown in the past. If you change the config at runtime, this could lead to exceptions to the users!

We now introduce the “throwConfigExceptions” option:

<nlogthrowConfigExceptions="true|false|<empty>">
LogManager.ThrowConfigExceptions=true|false|null
  • If set to true, if will throw exceptions for configuration errors. Set this to true if you like the behaviour from NLog 4.2 and ealier.
  • If set to empty (or null in the API), this option will follow the “throwExceptions” option (previous section)
  • If set to false, don’t throw exceptions for configuration errors.

Also throwing exceptions for a configuration error
could lead to System.TypeInitializationException which is bad and confusing as sending info with the exception is difficult or sometimes impossible - see stackoverflow.

API improvements

There are some notable changes in the API, so it’s easier to create or edit the configuration in C# (or other .Net language). The existence of the SimpleConfigurator was a hint things weren’t simple enough ;)

Changes:

  • LogManager has now AddRule methods. See examples below.
  • Set the max log level in the LoggingRule constructor.
  • The name of the TargetAttribute is used as fallback for every target now.

LogManager now has AddRule methods

Rules can now be created directly in the LogManager. There are some overloads to keep things simple.

Before:

varconfig=newLoggingConfiguration();varfileTarget=newFileTarget();config.AddTarget("f1",fileTarget);config.LoggingRules.Add(newLoggingRule("*",LogLevel.Debug,LogLevel.Error,fileTarget));LogManager.Configuration=config;

now also possible:

varconfig=newLoggingConfiguration();varfileTarget=newFileTarget("f1");config.AddTarget(fileTarget);config.AddRule(LogLevel.Debug,LogLevel.Fatal,"f1");LogManager.Configuration=config;

or

varconfig=newLoggingConfiguration();varfileTarget=newFileTarget{name:"f1"};config.AddRule(LogLevel.Debug,LogLevel.Fatal,fileTarget);LogManager.Configuration=config;

Relative paths for fileTarget

FileTarget now supports relative paths. No need for ${basedir} in the file target anymore!

InternalLogger: write to System.Diagnostics.Trace

It’s now possible to write to let the internal logger write to System.Diagnostics.Trace. The trace is easy to follow within Visual Studio.

image

<nloginternalLogToTrace="true"

or c# InternalLogger.LogToTrace = true;

Other features

Smaller improvements

Targets

  • Mail Target: allow virtual paths for SMTP pickup
  • EventTarget: option to set the maximum length of the message and action (discard, split, truncate)
  • MethodCallTarget: allow optional parameters in called methods.
  • ConsoleTarget: regex cache is instead of compiled regex, for better memory usage. This is configurable.
  • Database target: doesn’t require “ProviderName” attribute when using <connectionStrings>

Layouts

  • RegistryLayout: support for layouts, RegistryView (32, 64 bit) and all root key names (HKCU/HKLM etc)

API

  • Allow to free CallContext in MappedDiagnosticsLogicalContext
  • LogFactory: add generic-type versions of GetLogger() and GetCurrentClassLogger()
  • Added Logger.Swallow(Task task)

Other

  • Unused targets will be logged to the internal logger
  • Config classes are now thread-safe.
  • InternalLogger: improved logging of exceptions (analogous to normal Logger)
  • More logging to the internal logger (e.g. Async wrapper and buffer wrapper)
  • Added timestamp options for the internal logger:
    • Added “internalLogIncludeTimestamp” option to <NLog>
    • Added “nlog.internalLogIncludeTimestamp” option <appSettings>
    • Added NLOG_INTERNAL_INCLUDE_TIMESTAMP environment setting
  • Read nlog.config from Android assets:
LogManager.Configuration=newXmlLoggingConfiguration("assets/nlog.config");

Bug fixes

Various bugs have been fixed in this version. The most noticeable:

  • ${callsite} works now for async methods!
  • A lot of Filetarget bug fixes regarding with archiving, locking and concurrent writing. See GitHub issues for all details. Most noticeable:
    • Use last-write-time for archive file name. This is far more stable. In the past there were some issues with unexpected archive filenames.
    • Fix: archiving won’t work when a there is a date in the filename
    • Fix: archiving not working properly with AsyncWrapper
    • Fix: footer for archiving
    • Fix: crashes with relative path without ${basedir}
    • Fix: archive files are never created when there are lot of writes in log file
  • NetworkTarget: fix possible deadlock
  • Fix autoreload nlog.config with parent configs.
  • WebServiceTarget: fix HTTP GET protocol
  • Bugfix: Internallogger creates folder, even when turned off
  • Fix possible Nullref in ${variable}
  • ${processtime}: incorrect milliseconds formatting
  • ${processtime}: fix incorrect negative time (rounding issue)

Thanks to!!

New NLog OWIN adapter has been released

$
0
0

We’re proud to announce that the former community project NLogAdapter is now part of NLog as NLog.Owin.Logging to provide a Microsoft.Owin.Logging.ILoggerFactory implementation for your OWIN pipeline.

Usage is as simple as:

PM > Install-Package NLog.Owin.Logging
usingNLog.Owin.Logging;publicclassStartup{publicvoidConfiguration(IAppBuilderapp){app.UseNLog();}}

NLog 4.3 has been released!

$
0
0

After three RC releases, NLog 4.3 has been released! With more than 150 issues closed, this is one of the largest release since years. Main features: Xamarin support, Windows Phone 8 support, improved error handling and logging of NLog self and a lot of bug fixes!

The release can be downloaded from NuGet.

Check for all the details the GitHub 4.3 milestone.

For those who have contributed to NLog, big thanks!

Features

This release contains the following features:

Support Windows Phone 8, Xamarin Android and Xamarin iOS (beta)

In NLog 4.3 support has been added for the following platforms: Windows Phone 8, Xamarin Android and Xamarin iOS. The support is still in beta as we didn’t get the unit tests running.

Not every feature is working on those platforms, for example auto reloading the configuration is not supported in Xamarin. A full overview of what is supported on each platform can be viewed on the wiki.

Consistent handling of exceptions (BEHAVIOUR CHANGE)

The logging and throwing of exceptions was previously inconsistent. Not all of it was logged to the internal logger and some times they got lost. For example, the async wrapper (or async attribute) was catching all exceptions without a proper rethrow.

This is bad as it is sometimes unclear why NLog isn’t working (got it myself multiple times). This has been fixed in NLog 4.3!

  • All exceptions are logged to the internal logger
  • The “throwExceptions” option will be respected in all cases

Advise: disable throwExceptions in production environments! (this the default)

<nlogthrowExceptions="false">

Control of exception throwing for configuration errors

The following is stated in multiple locations: > By default exceptions are not thrown under any circumstances.

This was not true for configuration errors - those were always rethrown in the past. If you change the config at runtime, this could lead to exceptions to the users!

We now introduce the “throwConfigExceptions” option:

<nlogthrowConfigExceptions="true|false|<empty>">
LogManager.ThrowConfigExceptions=true|false|null
  • If set to true, if will throw exceptions for configuration errors. Set this to true if you like the behaviour from NLog 4.2 and ealier.
  • If set to empty (or null in the API), this option will follow the “throwExceptions” option (previous section)
  • If set to false, don’t throw exceptions for configuration errors.

Also throwing exceptions for a configuration error
could lead to System.TypeInitializationException which is bad and confusing as sending info with the exception is difficult or sometimes impossible - see stackoverflow.

API improvements

There are some notable changes in the API, so it’s easier to create or edit the configuration in C# (or other .Net language). The existence of the SimpleConfigurator was a hint things weren’t simple enough ;)

Changes:

  • LogManager has now AddRule methods. See examples below.
  • Set the max log level in the LoggingRule constructor.
  • The name of the TargetAttribute is used as fallback for every target now.

LogManager now has AddRule methods

Rules can now be created directly in the LogManager. There are some overloads to keep things simple.

Before:

varconfig=newLoggingConfiguration();varfileTarget=newFileTarget();config.AddTarget("f1",fileTarget);config.LoggingRules.Add(newLoggingRule("*",LogLevel.Debug,LogLevel.Error,fileTarget));LogManager.Configuration=config;

now also possible:

varconfig=newLoggingConfiguration();varfileTarget=newFileTarget("f1");config.AddTarget(fileTarget);config.AddRule(LogLevel.Debug,LogLevel.Fatal,"f1");LogManager.Configuration=config;

or

varconfig=newLoggingConfiguration();varfileTarget=newFileTarget{name:"f1"};config.AddRule(LogLevel.Debug,LogLevel.Fatal,fileTarget);LogManager.Configuration=config;

Relative paths for fileTarget

FileTarget now supports relative paths. No need for ${basedir} in the file target anymore!

InternalLogger: write to System.Diagnostics.Trace

It’s now possible to write to let the internal logger write to System.Diagnostics.Trace. The trace is easy to follow within Visual Studio.

image

<nloginternalLogToTrace="true"

or c# InternalLogger.LogToTrace = true;

Other features

Smaller improvements

Targets

  • Mail Target: allow virtual paths for SMTP pickup
  • EventTarget: option to set the maximum length of the message and action (discard, split, truncate)
  • MethodCallTarget: allow optional parameters in called methods.
  • ConsoleTarget: regex cache is instead of compiled regex, for better memory usage. This is configurable.
  • Database target: doesn’t require “ProviderName” attribute when using <connectionStrings>

Layouts

  • RegistryLayout: support for layouts, RegistryView (32, 64 bit) and all root key names (HKCU/HKLM etc)

API

  • Allow to free CallContext in MappedDiagnosticsLogicalContext
  • LogFactory: add generic-type versions of GetLogger() and GetCurrentClassLogger()
  • Added Logger.Swallow(Task task)

Other

  • Unused targets will be logged to the internal logger
  • Config classes are now thread-safe.
  • InternalLogger: improved logging of exceptions (analogous to normal Logger)
  • More logging to the internal logger (e.g. Async wrapper and buffer wrapper)
  • Added timestamp options for the internal logger:
    • Added “internalLogIncludeTimestamp” option to <NLog>
    • Added “nlog.internalLogIncludeTimestamp” option <appSettings>
    • Added NLOG_INTERNAL_INCLUDE_TIMESTAMP environment setting
  • NLog reads NLog.Config from Android Assets.

Bug fixes

Various bugs have been fixed in this version. The most noticeable:

  • ${callsite} works now for async methods!
  • A lot of Filetarget bug fixes regarding with archiving, locking and concurrent writing. See GitHub issues for all details. Most noticeable:
    • Use last-write-time for archive file name. This is far more stable. In the past there were some issues with unexpected archive filenames.
    • Fix: archiving won’t work when a there is a date in the filename
    • Fix: archiving not working properly with AsyncWrapper
    • Fix: footer for archiving
    • Fix: crashes with relative path without ${basedir}
    • Fix: archive files are never created when there are lot of writes in log file
    • Fix: writing file to root wasn’t working
  • NetworkTarget: fix possible deadlock
  • Fix autoreload nlog.config with parent configs.
  • WebServiceTarget: fix HTTP GET protocol
  • Bugfix: Internallogger creates folder, even when turned off
  • Fix possible Nullref in ${variable}
  • ${processtime}: incorrect milliseconds formatting
  • ${processtime}: fix incorrect negative time (rounding issue)

Thanks to!!

NLog roadmap - .NET Core, structural logging & performance

$
0
0

We have the following releases planned for NLog:

NLog 4.4

no .NET Core, yet

Originally NLog 4.4 would have .NET Core support. We have released multiple alpha and beta releases with support .NET Core (or to be precise .NET Standard). Unfortunately, there is a show-stopper: the behavior of GetCurrentClassLogger is wrong and we can’t fix it as the StackTrace API is limited in .NET Core (see here). You can read more about it here. We will postpone .NET Core support to NLog 5.

Will this delay a RTM with .NET Core support? Yes. As long as the StackTrace API is missing, we can’t fix it. It seems that .NET Standard 2 (Q1 2017) will support the StackTrace API.

Better handling of invalid config

Currently, some mistakes in the config could lead to no logging at all. For example, if ${aspnet-item} is used in the file target and NLog.Web was not included, no files are written.

We will fix this in NLog 4.4 and we will replace the wrong part with an empty string. See this PR.

Easier extending

A lot of feature requests could be easily implemented by writing a custom target or layout renderer. Currently it’s a bit difficult to register your custom code. We will improve that. Also a custom layout renderer should be as easy as one line of code:

LayoutRenderer.RegisterLayoutRenderer("trace-identifier", (logEvent) =>  HttpContext.Current.TraceIdentifier );

Steam and byte pooling (performance)

Currently under development, thanks to @bjornbouetsmith and @snakefoot!

This change will decrease memory pressure and prevent (excessive) garbage collection.

For details, see PR 1397 and and PR 1663

NLog 4.5

Structural logging

We would like to support structural logging like Serilog. We are currently working on an own parser and renderer. More info here.

NLog 5

NLog 5 will have .NET Core support and we will push some small breaking changes.

NLog 6

NLog 6 will split all the functionality to multiple packages. Why is this not the case in NLog 5? Well the .NET Core support consists of more than 250 commits and almost 400 changed files. If something is broken by those changes, it’s easier to find the previous code if we won’t move all the code around!

NLog 4.4 is live!

$
0
0

NLog 4.4 contains new features, performance improvements and makes it easier to write custom components (e.g. targets, layout renderers) for NLog!

A lot of stuff has been contributed by the community! Thanks for making NLog great!

Main features

WebServiceTarget support for JSON & XML

The WebServiceTarget was always a bit odd as it was posting the data Form-encoded (application/x-www-form-urlencoded). This has now been fixed with the support for JSON and XML, just pick one!

Example

<targettype='WebService'name='ws'url='http://localhost:1234/logme'protocol='JsonPost'encoding='UTF-8'><parametername='param1'type='System.String'layout='${message}'/><parametername='param2'type='System.String'layout='${level}'/></target>

Injecting JSON serializer into NLog

With the support of JSON in the WebServiceTarget, it can be important to give the opportunity to choose your JSON serializer implementation. This implementation will be also used for all other JSON serialization in NLog, like the JsonLayout.

We really like JSON.NET, but we don’t like to depend on it! It’s a great library, but it can lead to issues with strong names and other versions in your project. See also the statement of RestSharp library (which is also a great library)

So we now have our own implementation, which is sufficient for most cases.

Do you like to choose your implementation? Implement SerializeObject(..) in IJsonSerializer and set it to ConfigurationItemFactory.JsonSerializer.

JSON layout support for all-event-properties

The JsonLayout has two new properties which will help you creating better JSON documents:

  • includeAllProperties: Include all events properties of a logevent? default: false. Introduced in NLog 4.4
  • excludeProperties: comma separated string with names which properties to exclude. Only used when includeAllProperties is true. Case sensitive. Default empty When a name contains a comma, single quote the value. E.g. ‘value,withquote’,value2. Introduced in NLog 4.4

Example:

<layoutxsi:type="JsonLayout"includeAllProperties="true"excludeProperties="BadPropertyName1, BadProperty2"><fieldname="message"layout="My message for you is this ${message}"/></layout>

Don’t stop logging when there is something wrong in the layout

Previously, if you made an error in a layout, e.g. typos:

<targetname="file"xsi:type="File"layout="${message} ${oops-I-made-a-typo}">

or just using a layout renderer from a non-included package, nothing got logged!

This is unneccesary and we are skipping the invalid parts now. The invalid parts are replaced with an empty string.

NB: If throwExceptions or throwConfigExceptions is true, there will be still an error thrown

Lamba Function layout renderers

Layout renders (those things between ${}) can help you writing context information.

Since NLog 4.4 there is a new way to create a custom layout renderer, which can be written on one line!

The new LayoutRenderer.Register accepts a lamba function, which accepts 1 or 2 parameters and should return a string.

  • 1 parameter: the logEventInfo.
  • 2 parameters: logEventInfo and the current NLog config.

Examples

//register ${text-fixed}LayoutRenderer.Register("test-fixed",(logEvent)=>"2");//register ${trace-identifier}LayoutRenderer.Register("trace-identifier",(logEvent)=>HttpContext.Current.TraceIdentifier);//Using logEventInfo, ${message-length}LayoutRenderer.Register("message-length",(logEvent)=>logEvent.Message.Length);//Using config, ${targetCount}LayoutRenderer.Register("targetCount",(logEvent,config)=>config.AllTargets.Count);

See the wiki

Make it easier to register custom layout / target / layoutrendeners

There is a new syntax introduced so it’s easier to register your custom extensions:

//targetTarget.Register<MyNamespace.MyFirstTarget>("MyFirst");//genericTarget.Register("MyFirst",typeof(MyNamespace.MyFirstTarget));//OR, dynamic//layout rendererLayoutRenderer.Register<MyNamespace.MyFirstLayoutRenderer>("MyFirst");//genericLayoutRenderer.Register("MyFirst",typeof(MyNamespace.MyFirstLayoutRenderer));//dynamic//layoutLayout.Register<MyNamespace.CsvLayout>("csv");//genericLayout.Register("csv",typeof(MyNamespace.CsvLayout));//dynamic

For more info, see the wiki

Collection types for custom extensions

Custom Targets, layout etc. can have properties. There are only limitations if you’d like to set them from the XML config.

The following types are supported:

Allowed types

Allowed types for Targets, Layouts and Layout renderers.

  • C# types: e.g. bool, char, decimal, double, float, int, uint, etc.
  • Enums (use short name)
  • Encoding
  • CultureInfo
  • Type
  • LineEndingMode
  • Uri
  • NLog types: Layout, SimpleLayout& ConditionExpression
  • Types which has an implicit conversion from string
  • Types which are using TypeDescriptor from string (not Silverlight)
  • Collections, introduced in NLog 4.4. See section Collection types

Collection types

Introduced in NLog 4.4, the following collection types can be used.

Usage in XML: comma separated string. If the value contains a comma, single quote the whole value.

Examples:

  • value="one arg"
  • value="1,2"
  • value="value1,'value2, with comma'"

Collections of type:

  • IList<T> / IList
  • IEnumerable<T> / IEnumerable
  • ISet<T> / HashSet<T>

with the following types:

  • C# built in types (string, int, double, object)
  • enum (use short name)
  • culture, encoding, Type
  • not supported: Layout

Not supported:

  • Arrays
  • Non-generic List
  • Non-gereric IList
  • Custom class implementing/inheriting from the collection classes/interfaces. (because of performance)

PS: .NET 3.5 has HashSet but no ISet

Added condition to AutoFlushWrappper

Something you would like to flush in special cases only, e.g. sending a mail when there is an error. Of course you would like to have the trace logs in your mail too, as that can help identifying the problem!

This is now possible by using the Condition property on AutoFlushWrappper

Example:

<targetname="file"xsi:type="AutoFlushWrapper"condition="level >= LogLevel.Error"><targetxsi:type="BufferingWrapper"..><targetname="gmail"xsi:type="Mail"smtpServer="smtp.gmail.com"smtpPort="587"smtpAuthentication="Basic"/></target></target>

LimitingTargetWrapper

Like sending mail but not every 10 seconds? With the LimitingTargetWrapper you can control the maximum events per interval.

Example, max 5 messages per 10 minutes

<targetname='limiting'type='LimitingWrapper'messagelimit='5'interval='0:10:00'><targetname="gmail"xsi:type="Mail"smtpServer="smtp.gmail.com"smtpPort="587"smtpAuthentication="Basic"/></target>

WindowsMultiProcessFileAppender

In Windows there is a new file writing implementation. From tests we have 10-40% performance increase!

WebServiceTarget & ${UrlEncode} - Added standard support for UTF8 encoding, added support for RFC2396 & RFC3986

The URL encoding for the WebServiceTarget was not behaving to any RFC as far as we know. This has been changed!

For the WebServiceTarget & ${UrlEncode}, NLog will by default encode parameters as UTF8 and escape special characters according to Rfc2396.

Also the following properties have been added to WebServiceTarget & ${UrlEncode}

  • escapeDataRfc3986 - To escape data according to standard Rc3986, set this option to true
  • escapeDataNLogLegacy - To escape data according to the old non-standard NLog style, set this option to true

Other additions and changes

  • ${exception} - Added support for AggregateException
  • Keeping variables during configuration reload (optional)
  • Layout processinfo with support for custom Format-string
  • DetectConsoleAvailable on (colored)Console disabled by default
  • Callsite: added includeNamespace option

Bugfixes:

  • Writing to the same file from multiple processes does not function when archiving with concurrentWrites="true" and keepFileOpen="true"
  • NLog throws ConfigurationErrorsException when appsettings has invalid XML.

Other:

  • Improved [Obsolete] warnings - include the Nlog version when it became obsolete
  • FileTarget - Close stale file handles outside archive mutex lock #1513

THANKS!

Thanks for the contributions!

  • @aireq
  • @AndreGleichner
  • @ie-zero
  • @Jeinhaus
  • @nazim9214
  • @snakefoot
  • @tetrodoxin

What’s up Next?

Structural logging!

We could use your help to introduce this feature soon!

Like to help with coding or testing? Please let us know!

Viewing all 75 articles
Browse latest View live


Latest Images