Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

NLog LayoutRenderer for Assembly Version

5.00/5 (2 votes)
22 Nov 2012CPOL 15.8K  
NLog LayoutRenderer for Assembly Version

This post will be short and is inspired by Robert’s comment under my previous post (Thanks for it!). Robert pointed (and I completely agree) that it might be useful to have application assemblies versions listed in the log output.

So here comes AssemblyVersionLayoutRenderer:

C#
[LayoutRenderer("asmver")]
[ThreadAgnostic]
public class AssemblyVersionLayoutRenderer : LayoutRenderer
{
    /// <summary>
    /// Specifies the assembly name for which the version will be displayed.
    /// By default the calling assembly is used.
    /// </summary>
    public String AssemblyName { get; set; }
    
    private String asmver;
    private String GetAssemblyVersion() {
        if (asmver != null) {
            return asmver;
        }
    
        InternalLogger.Debug("Assembly name '{0}' not yet loaded: ", AssemblyName);
        if (!String.IsNullOrEmpty(AssemblyName)) {
            // try to get assembly based on its name
            asmver = AppDomain.CurrentDomain.GetAssemblies()
                                  .Where(a => String.Equals(a.GetName().Name, 
                                  AssemblyName, StringComparison.InvariantCultureIgnoreCase))
                                  .Select(a => a.GetName().Name + " v" + 
                                  a.GetName().Version).FirstOrDefault();
            return asmver == null ? String.Format("<{0} not loaded>", 
            AssemblyName) : asmver;
        }
        // get entry assembly
        var entry = Assembly.GetEntryAssembly();
        asmver = entry.GetName().Name + " v" + entry.GetName().Version;
        return asmver;
    }

    /// <summary>
    /// Renders the current trace activity ID.
    /// </summary>
    /// <param name="builder">The <see cref="StringBuilder"/> 
    /// to append the rendered data to.</param>
    /// <param name="logEvent">Logging event.</param>
    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        builder.Append(GetAssemblyVersion());
    }
}

To use it, simply add ${asmver} to your layout configuration. As you can read from the above snippet, you may specify which assembly version should be added to the output (by default entry assembly is used) and it’s completely legal to have more than one AssemblyVersionLayoutRender in your layout. Example configuration:

XML
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        internalLogToConsole="true" 
        internalLogLevel="Debug" throwExceptions="true">
    <extensions>
      <add prefix="lld" assembly="LowLevelDesign.NLog.Ext" />
    </extensions>
    <targets>
      <target name="console" xsi:type="ColoredConsole" layout="${longdate}|
       ${lld.asmver:assemblyname=NLog}|${lld.asmver}|${logger}|${uppercase:${level}}|
       ${message}${onexception:|Exception occurred\:${exception:format=tostring}}" />
    </targets>
    <rules>
      <logger name="TestLogger" 
      minlevel="Debug" writeTo="console" />
      <logger name="TestSource" 
      minlevel="Debug" writeTo="console" />
    </rules>
  </nlog>

will produce the following output for my TestNLog application:

2012-11-22 07:18:13.7340|NLog v2.0.0.0|TestNLog v0.0.0.0|TestLogger|INFO|Start
In the middle of tracing
2012-11-22 07:18:13.8200|NLog v2.0.0.0|TestNLog v0.0.0.0|TestLogger|ERROR|
Error occured|Exception occurred:System.Exception: TestException
2012-11-22 07:18:13.8360|NLog v2.0.0.0|TestNLog v0.0.0.0|TestLogger|INFO|End

I updated the NLog project on my samples website so if you would like to use the new layout renderer, feel free to download it. And as usual, if you have any suggestions or ideas, I will be more than happy to see them in the comments. :)

Filed under: CodeProject, Logging with NLog

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)