在 Hangfire.io 中登录到 NLog
本文关键字:NLog 登录 Hangfire io | 更新日期: 2023-09-27 18:31:46
我目前正在使用Hangfire在Windows服务中运行一些作业。 作业是从 WebAPI 触发的。
当所有作业都成功时,我的系统当前工作正常,但是当发生异常时,我没有记录。 有没有人有使用自定义记录器从 Hangfire 接收消息的经验?
我的记录器是一个基本的 NLog 接口:
public class Logger : ILogger
{
public readonly NLog.Logger logger;
public Logger(string name)
{
if (LogManager.Configuration == null)
{
FallbackInitialisation();
}
logger = LogManager.GetLogger(name);
}
public Trace(string message)
//etc.
}
我正在我的Windows服务中配置我的Hangfire作业服务器,如下所示:
SqlServerStorage storage = new SqlServerStorage("myConnectionString");
BackgroundJobServerOptions options = new BackgroundJobServerOptions();
m_server = new BackgroundJobServer(options, storage);
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });
根据 hangfire 文档,我只是尝试通过添加所需的引用来遵循它,并在作业服务器设置后添加以下内容,但是仍然没有生成日志:
var properties = new NameValueCollection();
properties["configType"] = "INLINE";
LogManager.Adapter = new NLogLoggerFactoryAdapter(properties);
我只是通过在作业调用的方法中throw new Exception()
来模拟异常。作业是在 webAPI 调用中创建的,如下所示:
[HttpGet]
public void TestStartJob()
{
m_logger.Trace("TestStartJob");
BackgroundJob.Enqueue(() => m_service.TestStartJob());
}
我正在寻找的是,是否有人在正确配置日志记录以与 Hangfire 一起使用方面有任何经验。
我已经设法通过使用以下版本的 nuget 包来解决此问题:
NLog - 3.1
Common.Logging - 2.2.0
JVW.Logging.CommonLoggingNLogAdapter - 1.0.0.1
然后按此配置日志记录
var properties = new NameValueCollection();
properties["configType"] = "INLINE";
Common.Logging.LogManager.Adapter = new NLogFactoryAdapter(properties);