Nlog: Exception.HResult gives unknown exception in internal.txt

Created on 18 Nov 2019  路  9Comments  路  Source: NLog/NLog

NLog version: 4.9.0

Platform: .NET Core 3.0

Current NLog config (xml or C#, if relevant)

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="c:\temp\internal.txt">

  <!-- define various log targets -->
  <targets async="true">
    <!-- write logs to file -->
    <target xsi:type="File" name="error" fileName="D:\Dev\dotnet\Core\Logs\Logging2.2\error-log-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|Type:${exception:format=Type}|HResult:${exception:format=hresult}|${message}" />

    <!-- set up a blackhole log catcher -->
    <target xsi:type="Null" name="blackhole" />

  </targets>

  <rules>

    <!-- Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" level="Info" writeTo="blackhole" final="true" />
    <!-- Log errors to the error email buffer and error file -->
    <logger name="*" minlevel="Error" writeTo="error" />
  </rules>
</nlog>

Program.cs

```C#
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog();
}
**Startup.cs**

```C#
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddControllersWithViews()
                .AddNewtonsoftJson();
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthentication();

            ///This is in place of app.UseMvc(... below
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });
        }
    }

HomeController.cs

```C#
public class HomeController : Controller
{
private readonly ILogger _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogCritical(new NullReferenceException(), "FATAL Error!");
        try
        {
            throw new NullReferenceException();
        }
        catch (Exception e)
        {
            _logger.LogError(e, e.Message);
        }

        return View();
    }

}

**Log file**

2019-11-18 14:12:26.0470|Logger2._2.Controllers.HomeController|ERROR|Type:System.NotImplementedException|HResult:|The method or operation is not implemented.
2019-11-18 14:15:47.5842|Logger2._2.Controllers.HomeController|FATAL|Type:System.NullReferenceException|HResult:|FATAL Error!
2019-11-18 14:16:09.4641|Logger2._2.Controllers.HomeController|ERROR|Type:System.NullReferenceException|HResult:|Object reference not set to an instance of an object.

- What is the current result?
Nothing is being outputted when ${exception:format=HResult} or ${exception:format=hresult} is used. Is this because it's a number format?
${exception:format=Type} is correctly outputting the exception type.


- What is the expected result?
I expect to see the value of the HResult property outputted. When I debug the error, the HResult is showing as -2147467261. This isn't being outputted in the log.

- Did you checked the [Internal log](https://github.com/NLog/NLog/wiki/Internal-Logging)?
Yes, it says:

2019-11-18 14:08:52.9552 Warn Unknown exception data target: HResult
```

  • Are there any workarounds? Yes
  • Is there a version in which it did work? 4.9.0 is the first version I've tried to use it
bug question

Most helpful comment

I see the error:

#if NET45

It should have been:

#if NET_45

All 9 comments

Hi! Thanks for opening your first issue here! Please make sure to follow the issue template - so we could help you better!

Hi,

You need to add the NLog 4.6.8 package:

<PackageReference Include="NLog" Version="4.6.8" />

NLog.Web.AspNetCore 4.9 uses NLog 4.6.7 indirectly. The HResult option is added in NLog 4.6.8, see https://github.com/NLog/NLog/wiki/Exception-Layout-Renderer

As this is a newer version of NLog and also the same major version (4.x.x), you could safely update the NLog package.

@304NotModified Thanks for the response. I've added this project reference and the warning isn't outputted to the internal.txt file any more but still nothing outputs to the log for:
```C#
${exception:format=HResult}

```xml
    <PackageReference Include="NLog.MailKit" Version="3.1.0" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
    <PackageReference Include="NLog" Version="4.6.8" />

Please check the version of NLog in your bin folder. Is it really 4.6.8?

Also make sure there is an actual HResult. If default value (0 or 1) then it output empty-string (Caters for JsonLayout that will skip attributes that renders nothing)

@304NotModified @snakefoot

Bin has nlog v4.6.8 included:

image

Exception is throwing with a HResult

image

Referencing HResult on layout after string placeholder "Res: "

<target xsi:type="Mail" name="key-error-instant-mail">
          <subject>Error on ${configsetting:cached=True:name=WebsiteConfig.ShortName} (${left:inner=${environment:ASPNETCORE_ENVIRONMENT}:length=1}) ${newline}</subject>
          <layout>Res: ${exception:format=HResult} ${longdate} ${level:uppercase=true:padding=5} - ${logger:shortName=true} - ${message} ${exception:format=tostring} ${newline}</layout>
        </target>

HResult isn't outputted after Res: in the email

image

Package inclusion

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="3.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
    <PackageReference Include="NLog.MailKit" Version="3.1.0" />
    <PackageReference Include="NLog" Version="4.6.8" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
  </ItemGroup>

I'm just working in a demo solution so happy to provide it to you if you can give me upload / email details?

Thanks for the detailed info!

A demo would be great! You could create a repo or zip it and include it here. Then we will check it!

I see the error:

#if NET45

It should have been:

#if NET_45

Created PR #3700

Was this page helpful?
0 / 5 - 0 ratings

Related issues

imanushin picture imanushin  路  3Comments

MaximRouiller picture MaximRouiller  路  3Comments

smeegoan picture smeegoan  路  3Comments

sszost picture sszost  路  3Comments

BobSeu picture BobSeu  路  3Comments