.NET core: Hangfire setup with NLog

本小妞迷上赌 提交于 2019-12-11 17:54:49

问题


I have an .NET Core 2 powered API that I would like to add Hangfire to. The project is already using NLog to log to a MySQL database and it works fine, but when I try to setup and use Hangfire I get the following error:

Method not found: 'Hangfire.Logging.ILog Hangfire.Logging.LogProvider.GetCurrentClassLogger()'.

The Hangfire dashboard works, but I get that error when trying to enqueue my first job like this:

BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget"));

I have read the Hangfire documentation over at: http://docs.hangfire.io/en/latest/configuration/configuring-logging.html

and it says:

Starting from Hangfire 1.3.0, you are not required to do anything, if your application already uses one of the following libraries through the reflection (so that Hangfire itself does not depend on any of them). Logging implementation is automatically chosen by checking for the presence of corresponding types in the order shown below.

That list includes NLog, so apparently I am doing something wrong.

In my csproj I have:

<PackageReference Include="Hangfire" Version="1.6.19" />
<PackageReference Include="Hangfire.MySqlStorage" Version="1.0.5" />
<PackageReference Include="MySql.Data" Version="8.0.11" />
<PackageReference Include="NLog" Version="4.5.3" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.5.2" />

In Startup.cs and ConfigureServices I have:

services.AddHangfire(config => config.UseStorage(new MySqlStorage(appSettings.GetConnectionString("HangfireConnectionString"))));

and in Configure I have:

loggerFactory.AddNLog();
env.ConfigureNLog("nlog.config");

app.UseHangfireDashboard();
app.UseHangfireServer();

My nlog.config contains:

<target name="database" xsi:type="Database" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server=localhost;Database=nlog;user id=root;password=;SslMode=none;">

and it does log to the MySQL database without Hangfire, so that seems to be working.

Looking at the Nlog documentation at:

https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

They seem to add NLog in Program.cs instead of Startup.cs, so I tried that approach as well, but I still get the same error.


回答1:


Looks like the Hangfire.MySqlStorage library was the root cause of this error. After changing to Hangfire.MySql.Core everything works great without any changes being made to NLog.



来源:https://stackoverflow.com/questions/49933967/net-core-hangfire-setup-with-nlog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!