Ads by Lake Quincy Media
Gibraltar - Learn about the best analysis tool for NLog

Archive for the ‘News’ Category

Using NLog with Mono

After releasing NLog 2.0 a number of people have reported problems with running on latest versions of Mono. Basically at the end of program execution (after the Main() has finished) the program locks up waiting for NLog logs to be flushed, so mono process never completes and needs to be killed.

This behavior is only specific to NLog 2.0 – NLog 1.0 did not exhibit this behavior. It seems to be related to threading and timers used by NLog 2.0 which are somehow not available in Mono when the program is about to be terminated. The same code works with .NET just fine. I haven’t fully investigated this issue – maybe Mono folks can see if this issue can be fixed in Mono itself?

Anyway – there is a simple way prevent the deadlock: just make sure you set LogManager.Configuration property to null before your application exits. This will cause Flush() to be executed before Main() finishes and will prevent appdomain unload handler from locking up.

In NLog 2.0.0.2005 (nightly build – available on CodePlex, source code on GitHub as usual) I have disabled automatic flushing of logs in Mono builds. That means that when running on Mono (same as with Silverlight and .NET Compact Framework), it is developer’s responsibility to flush logs before program exits. I’m hoping to restore automatic flushing behavior when the issue is fixed in Mono or if I can find a way to work around the problem.

Ads by Lake Quincy Media

NLog 2.0 has been released!

It is my great pleasure to announce that NLog 2.0 has been released.

NLog 2.0 release is focused on adding support for new platforms (Silverlight, .NET Framework 4, Windows Phone 7.x), improving logging architecture and manageability and addressing most frequently reported user issues.

Binaries can be downloaded from CodePlex.
Sources are available at GitHub.
NuGet packages are also available.

You can read the release notes at http://nlog-project.org/nlog-2-0-release-notes.

NLog 2.0 Release Candidate is now available

It is our pleasure to announce that the Release Candidate (RC) of NLog 2.0 is now available for download. This is the last milestone before NLog 2.0 final release.

  • Binary downloads are available on CodePlex
  • Source code on GitHub
  • Full release notes can be found here.

Please download the release and report any problems you may find. Assuming no critical issues are found, NLog 2.0 will be released within a month from the RC release.

Exception logging enhancements

One of the frequent feature requests I’ve been getting was to improve the way exceptions are logged. Recent builds of NLog 2.0 include several usability enhancements that should make working with exceptions much easier.

Conditional formatting

Conditional logging allows you to make your layouts somewhat more dynamic – you can include/exclude fields based on conditions, provide default values and so on. In order to achieve this, you have 3 new layout renderers at your disposal.

${onexception:INNER} -  output

To render a layout when the exception is being logged, use ${onexception:INNER}, it will output INNER only when current log event includes an exception (in other words when it was emitted using any of the Logger.*Exception() methods. INNER can include other layouts, for example:

<targets>
  <target name="f" type="File" layout="${message}${onexception:EXCEPTION OCCURRED\:${exception:format=tostring}}" />
</targets>

It will output log message, but in case of exception, it will also log detailed exception information prefixed with "EXCEPTION OCCURRED:".

${when} – advanced conditional formatting

You can also conditionally include or exclude layout renderers based on conditions by using ${when} layout renderer wrapper. You can even use ambient property called "when" as if it were declared on any other layout renderer:

For example ${message:when=logger==’logger’} will only print the message when it was emitted by ‘logger’. The conditions can be much more complex – you have the full power of conditions language at your disposal.

${whenEmpty} – empty value coalescing

Sometimes you may want to print an indication that a layout renderer has produced an empty value, instead of completely skipping its output. That’s where ${whenEmpty} layout renderer wrapper comes in handy. You can also use the ambient property form, just by using ‘whenEmpty’ property in any other layout renderer. For example:

${message:whenEmpty=(no message)}

Inner exception logging

Recent builds also include improvements to ${exception} layout renderer which now lets you output inner exceptions. There are several new properties:

  • ${exception:maxInnerExceptionLevel=N} -  controls how many inner exceptions are logged. defaults to zero for backwards compatibility.
  • ${exception:innerExceptionSeparator=TEXT} – defines text that separates inner exceptions. Defaults to new line string (platform specific).
  • ${exception:innerFormat=FORMATSTRING} – defines the format of inner exceptions the same way that ${exception:format=FORMATSTRING} defines the format of the top-level exception. If this parameter is not specified, the same format is used for both top-level and inner exceptions.

A complete usage example is:

<targets>
  <target name="f" type="File" layout="${message}${onexception:EXCEPTION OCCURRED\:${exception:format=type,message,method:maxInnerExceptionLevel=5:innerFormat=shortType,message,method}}" />
</targets>

This will print top-level exception with full type name, message and method that raised the exception, but for inner exceptions only short type name is used instead.

As always, comments and suggestions are welcome.

Simplifying NLog.Extended.dll usage

I’d like to let you know about small simplification to using targets and layout renderers from NLog.Extended.dll. Previously you had to register them using configuration section:

<extensions>
  <add assembly="NLog.Extended" />
</extensions>

Starting with today’s Nightly build, this is no longer required – you can simply use extended items without extra registration (exactly like it worked in NLog 1.0). The only change is that you must have NLog.Extended.dll in the same directory as NLog.dll – you will get exception if it’s not present.

If you need NLog.Extended, please give this feature a try and report any issues you find.

NLog for Windows Phone 7

This week I have checked in a port of NLog 2.0 for Windows Phone 7. It’s still very experimental and the intention of this release is to get feedback from people. Please use at your own risk.

Current build supports 8 targets:

  • Console – can be used to write logs to the console (only works in Emulator – see this post for instruction on how to enable console output)
  • Memory – stores traces in memory
  • MethodCall – runs user-provided method for each log message
  • Network, NLogViewer and Chainsaw – write XML-formatted log event over the network. Only HTTP:// and HTTPS:// protocols are supported.
  • WebService – sends log events to a web service using SOAP or POST
  • LogReceiverService – sends log events to LogReceiver web service using WCF

Note that File target and several others are not included because of current constraints of the platform APIs.

Here is a simple step-by-step tutorial for adding NLog to your WP7 app:

  1. Download and install the bits

    • Go to http://nlog.codeplex.com/releases and download one of the recent nightly builds – choose build later than 2011/1/9
    • Pick a package named = NLog2-All-*.msi (includes builds for all platforms – recommended) or NLog2-WP-*.msi (which includes only WP7 bits).
    • Run the setup and wait – setup will add code snippets and templates for all development environments you have on the machine, which can take some time (couple minutes, so be patient)
  2. Add NLog  to your Windows Phone app project

    • Open your project
    • Add NLog.config to your project – the easiest way is to select ‘Add new item’ and choose ‘Empty NLog Configuration File’ from the ‘NLog’ section.
      NLogWP7AddNewItem
    • This will also add a reference to NLog:
      NLogWP7WithReference
    • If you prefer, you manually add reference to "C:\Program Files (x86)\NLog\Silverlight for Windows Phone 7\NLog.dll" instead and create NLog.config manually
    • One last thing is changing Build Action for NLog.config to ‘Content’ (this ensures that the file will be included in the XAP package).
  3. Set logging configuration

    In this tutorial we will use LogReceiverService target, but you can use any other target supported by NLog. To do this open NLog.config and paste the following configuration:

    <?xml version="1.0" encoding="utf-8" ?>
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    
        <targets>
          <target xsi:type="LogReceiverService" name="webService" endpointAddress="http://localhost:5000/LogReceiver.svc"/>
        </targets>
    
        <rules>
          <logger name="*" minlevel="Debug" writeTo="webService" />
        </rules>
    </nlog>
  4. Emit log messages

    To emit log messages you need to get a Logger instance from LogManager and call one of the log methods. See .NET_Logging_API for more information. Let’s add some logging code to MainPage.xaml.cs:

    namespace WindowsPhoneApplication2
    {
        using System.Windows;
        using Microsoft.Phone.Controls;
    
        public partial class MainPage : PhoneApplicationPage
        {
            private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    
            // Constructor
            public MainPage()
            {
                InitializeComponent();
                logger.Info("Main page loaded.");
            }
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                logger.Debug("Button 1 clicked.");
            }
    
            private void button2_Click(object sender, RoutedEventArgs e)
            {
                logger.Debug("Button 2 clicked.");
            }
        }
    }

    When you run the code, log messages will be sent to http://localhost:5000/LogReceiver.svc

  5. Receive log messages

    In order to receive log messages you need to have an endpoint that implements ILogReceiverServer contract. NLog comes with an example that does just that and listens on (incidentally) http://localhost/LogReceiver.svc , or if you prefer you can implement your own server. You can find it the example in the source code under examples\NLogReceiverForwarderService. The sample will basically forward NLog messages received from the network through NLog running on the server machine.

    • Download NLog source code
    • Open the project file examples\NLogReceiverForwarderService\NLogReceiverForwarderService.csproj (Visual Studio needs to be running as an Administrator)
    • Edit NLog.config and adjust log outputs as necessary.
    • Run the project. Notice how when you click on buttons in your Windows Phone 7 application, the logs are displayed on your console:

      LogForwarderOutput
  6. Let’s do more…

    Having rich NLog do log routing on both client and server opens a lot of possibilities. You can for example send much richer information from the client to the server. In order to do this we’ll be using parameters. Let’s modify client side configuration to send thread id along with each log message:

    <?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">
    
        <targets>
          <target xsi:type="LogReceiverService" name="webService" endpointAddress="http://localhost:5000/LogReceiver.svc">
            <parameter name="t" layout="${threadid}" />
          </target>
        </targets>
    
        <rules>
          <logger name="*" minlevel="Debug" writeTo="webService" />
        </rules>
    </nlog>

    On the server side, we can now extract ‘t’ parameter using ${event-context} layout renderer. Let’s also add timestamp to each message:

    <?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">
    
        <targets>
            <target name="console" xsi:type="Console" layout="${longdate} ${message} ${event-context:t}" />
        </targets>
    
        <rules>
            <logger name="*" minlevel="Debug" writeTo="console" />
        </rules>
    </nlog>

    Now when you restart both client and server you should see this picture – we can now see that all log events were sent from thread #2 – the UI thread of the Silverlight application.

    LogForwarderOutput2

I would love to hear your feedback about this build and using NLog in Windows Phone 7 applications in general. Please use Forum for any questions or suggestions or Issue Tracker if something does not work correctly.

NLog 2.0 Beta 1 has been released

It is my pleasure to announce that NLog 2.0 Beta 1 has been released.

NLog 2.0 release is focused on adding support for new platforms (Silverlight, .NET Framework 4), improving logging architecture and manageability and addressing most frequently reported user issues.

The following platforms are supported in this release:

  • .NET Framework 2.0 SP1 and above, 3.5 (Client and Extended profiles), 4.0 (Client and Extended profiles)
  • Silverlight 2.0, 3.0, 4.0
  • .NET Compact Framework 2.0, 3.5
  • Mono 2.x profile

Read full release notes:
http://nlog-project.org/nlog2-beta1-release-notes

Download Beta 1 bits on CodePlex:
http://nlog.codeplex.com/releases/view/52957

Source code is available on GitHub:
http://github.com/jkowalski/NLog/

Bugs can be reported on CodePlex:
http://nlog.codeplex.com/workitem/list/basic

Discuss on forum:
http://nlog-project.org/forum

Subscribe to NLog RSS feed:
http://nlog-project.org/feed

Follow @JarekKowalski on Twitter:
http://twitter.com/JarekKowalski

Deploying NLog configuration files

Some of the targets supported by NLog require installation to be performed on the machine before the target can be used. For example, when logging to a database, a DBA needs to create the necessary tables, when logging to event log or performance counter, administrator of the machine must create them before the application can write to them.

NLog 2.0 comes with a new tool and APIs that lets you manage installation and uninstallation of objects which support logging.

Say you want to write logs to:

  • local SQLEXPRESS database
  • Event Log on the local machine
  • increase performance counter each time log message occurs.
  • With NLog 2.0, you can embed installation/uninstallations steps directly in the log configuration file, like in the following example:

    <?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">
      <targets>
        <target xsi:type="Database" name="db">
          <!-- SQL command to be executed for each entry -->
          <commandText>INSERT INTO [LogEntries](TimeStamp, Message, Level, Logger) VALUES(getutcdate(), @msg, @level, @logger)</commandText>
    
          <!-- parameters for the command -->
          <parameter name="@msg" layout="${message}" />
          <parameter name="@level" layout="${level}" />
          <parameter name="@logger" layout="${logger}" />
    
          <!-- connection string -->
          <dbProvider>System.Data.SqlClient</dbProvider>
          <connectionString>server=.\SQLEXPRESS;database=MyLogs;integrated security=sspi</connectionString>
    
          <!-- commands to install database -->
          <install-command>
            <text>CREATE DATABASE MyLogs</text>
            <connectionString>server=.\SQLEXPRESS;database=master;integrated security=sspi</connectionString>
            <ignoreFailures>true</ignoreFailures>
          </install-command>
    
          <install-command>
            <text>
              CREATE TABLE LogEntries(
              id int primary key not null identity(1,1),
              TimeStamp datetime2,
              Message nvarchar(max),
              level nvarchar(10),
              logger nvarchar(128))
            </text>
          </install-command>
    
          <!-- commands to uninstall database -->
          <uninstall-command>
            <text>DROP DATABASE MyLogs</text>
            <connectionString>server=.\SQLEXPRESS;database=master;integrated security=sspi</connectionString>
            <ignoreFailures>true</ignoreFailures>
          </uninstall-command>
        </target>
    
        <target xsi:type="EventLog" name="eventLog" source="NLog Demo"
                layout="${message}${newline}Call site: ${callsite:className=true:methodName=true}${newline}Logger: ${logger}">
        </target>
    
        <target xsi:type="PerfCounter" name="pc1" categoryName="My Log" counterName="My Counter">
        </target>
    
      <rules>
        <logger name="*" minlevel="Trace" writeTo="db,eventLog,pc1" />
      </rules>
    </nlog>

    In order to deploy the database, event log and performance counter, you can use simply use InstallNLogConfig.exe tool that comes with NLog. Open elevated command prompt and run the following command:

    > InstallNLogConfig.exe c:\path\to\NLog.config
    Installing 'Database Target[db]'
    Finished installing 'Database Target[db]'.
    Installing 'EventLog Target[eventLog]'
    Finished installing 'EventLog Target[eventLog]'.
    Installing 'PerfCounter Target[pc1]'
    Finished installing 'PerfCounter Target[pc1]'.

    Uninstalling is equally easy:

    > InstallNLogConfig.exe" -u c:\path\to\NLog.config 
    Uninstalling 'Database Target[db]'
    Finished uninstalling 'Database Target[db]'.
    Uninstalling 'EventLog Target[eventLog]'
    Finished uninstalling 'EventLog Target[eventLog]'.
    Uninstalling 'PerfCounter Target[pc1]'
    Finished uninstalling 'PerfCounter Target[pc1]'.

    Passing parameters to installation

    Sometimes there is a need to pass parameters to the installation routing, which should not be normally visible in the NLog.config file. One example might be DBA username and password for connecting to the database. You can pass parameters on the command line by using –p NAME=VALUE option:

    > InstallNLogConfig.exe" –p ADMIN_USER=sa –p ADMIN_PASSWORD=megaSecret1234 c:\path\to\NLog.config 

    The parameters are accessible using  ${install-context} layout renderer. For example, we can easily modify the above example to use SQL authentication where user name and password are passed from command line:

    <install-command>
      <text>CREATE DATABASE MyLogs</text>
        <connectionString>server=.\SQLEXPRESS;database=master;
                          user id=${install-context:ADMIN_USER};password=${install-context:PASSWORD}</connectionString>
        <ignoreFailures>true</ignoreFailures>
    </install-command>

    Installation API

    In order to install logging configuration, you can simply use Install() and Uninstall() methods on LoggingConfiguration object. They both take InstallationContext arguments, which can be used pass parameters and specify logging and other options:

    namespace NLog.Config
    {
        public sealed class InstallationContext : IDisposable
        {
            /// <summary>
            /// Gets or sets the installation log level.
            /// </summary>
            public LogLevel LogLevel { get; set; }
    
            /// <summary>
            /// Gets or sets a value indicating whether to ignore failures during installation.
            /// </summary>
            public bool IgnoreFailures { get; set; }
    
            /// <summary>
            /// Gets the installation parameters.
            /// </summary>
            public IDictionary<string, string> Parameters { get; private set; }
    
            /// <summary>
            /// Gets or sets the log output.
            /// </summary>
            public TextWriter LogOutput { get; set; }
        }
    }

    Typical installation code will look like this:

    using (var context = new InstallationContext())
    {
      var config = new XmlLoggingConfiguration("NLog.config");
    
      // output detailed installation logs
      context.LogLevel = LogLevel.Trace;
    
      context.Parameters["ADMIN_USER"] = "sa";
      context.Parameters["ADMIN_PASSWORD"] = "megaSecret1234";
    
      // write logs to a log file
      using (var logFile = File.CreateText("InstallLog.txt"))
      {
        context.LogOutput = logFile;
    
        config.Install(context);
      }
    }

    In order to support custom installation in your target or any other configuration item (such as layout, filter, etc.), you simply need to implement IIinstallable interface:

    public interface IInstallable
    {
      void Install(InstallationContext installationContext);
      void Uninstall(InstallationContext installationContext);
      bool? IsInstalled(InstallationContext installationContext);
    }

    See DatabaseTarget sources for example implementation.

    New exception handling rules in NLog 2.0

    NLog will introduce a change to logging exception handling and suppression. In NLog 1.0 all exceptions were disabled by default, but could be enabled by setting

    <nlog throwExceptions=”true>
    
    </nlog>

    or in code:

    LogManager.ThrowExceptions = true;

    This flag applied to configuration errors as well as runtime errors, which was problematic, because a simple configuration file typo could cause entire logging to be disabled silently.

    To address this, NLog 2.0 will treat configuration errors separately from runtime errors. There will be two kinds of exceptions:

    1. Configuration exceptions – raised during parsing of configuration file and wrapped in NLogConfigurationException. Such errors are fatal and will prevent your application from starting (this is the same as having malformed App.config or Web.config). The errors that cause this exception are:
      • syntax errors in NLog.config
      • invalid target names
      • invalid property names
      • invalid property values
    2. Runtime exceptions (such as permission issues, connection failures, etc.) – raised during logging and initialization and wrapped in NLogRuntimeException. They can be controlled by throwExceptions flag.

    I would love to hear your comments.

    Routing System.Diagnostics.Trace and System.Diagnostics.TraceSource logs through NLog

    I have recently added a trace listener class for NLog, which enables routing of System.Diagnostics.Trace and System.Diagnostics.TraceSource logs through your favorite log routing engine. This can be very useful for integrating components that don’t necessarily support logging through NLog as well as analyzing traces produced .NET Framework itself.

    By using NLog trace listener you can send those logs via email, save them to a database, file or to any other supported log target.

    Let’s create a simple example – application that makes network call. We will then enable network call tracing without touching a single line of code.

    namespace TraceDemo
    {
      using System.Net; 
    
      class Program
      {
        static void Main(string[] args)
        {
          var webClient = new WebClient();
          webClient.DownloadString("http://somehost/nosuchfile.txt");
        }
      }
    }

    As you can see the example is just using WebClient from System.Net namespace, and has no tracing-specific code. Internally WebClient is capable of outputting traces through System.Net trace source. To route those traces through NLog you need to assign a listener to each source in the application configuration file. It is convenient to define NLogTraceListener as a shared listener and reference by name in all sources that you need as in the following example:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.diagnostics>
        <sources>
          <source name="System.Net" switchValue="All">
            <listeners>
              <add name="nlog" />
            </listeners>
          </source>
          <source name="System.Net.Sockets" switchValue="All">
            <listeners>
              <add name="nlog" />
            </listeners>
          </source>
        </sources>
        <sharedListeners>
          <add name="nlog" type="NLog.NLogTraceListener, NLog" />
        </sharedListeners>
      </system.diagnostics>
    </configuration>

    Obviously you also need NLog.dll and NLog.config to be located in the application directory. For our purposes we’ll use simple configuration with single target:

    <nlog>
      <targets>
        <target name="console" type="ColoredConsole" layout="${longdate} ${windows-identity} ${message}" />
      </targets>
    
      <rules>
        <logger name="*" minlevel="Trace" writeTo="console" />
      </rules>
    </nlog>

    When you run this application, you will get nice color-coded trace that includes lots of diagnostics information straight from the guts of .NET Framework. Having access to detailed trace like this can be very helpful in diagnosing hard-to-reproduce problems that are often impossible to figure out with a debugger.

    image