You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Readarr/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs

87 lines
2.7 KiB

using System;
using NLog.Config;
using NLog;
using NLog.Targets;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Lifecycle;
11 years ago
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Messaging.Events;
namespace NzbDrone.Core.ProgressMessaging
{
11 years ago
public class ProgressMessageTarget : Target, IHandle<ApplicationStartedEvent>
{
private readonly IEventAggregator _eventAggregator;
private readonly IManageCommandQueue _commandQueueManager;
11 years ago
private static LoggingRule _rule;
private const string REENTRY_LOCK = "ProgressMessagingLock";
public ProgressMessageTarget(IEventAggregator eventAggregator, IManageCommandQueue commandQueueManager)
{
_eventAggregator = eventAggregator;
_commandQueueManager = commandQueueManager;
}
11 years ago
protected override void Write(LogEventInfo logEvent)
{
if (!ReentryPreventionCheck()) return;
11 years ago
var command = GetCurrentCommand();
11 years ago
if (IsClientMessage(logEvent, command))
{
_commandQueueManager.SetMessage(command, logEvent.FormattedMessage);
_eventAggregator.PublishEvent(new CommandUpdatedEvent(command));
11 years ago
}
MappedDiagnosticsContext.Remove(REENTRY_LOCK);
}
private CommandModel GetCurrentCommand()
{
var commandId = MappedDiagnosticsContext.Get("CommandId");
if (String.IsNullOrWhiteSpace(commandId))
{
11 years ago
return null;
}
return _commandQueueManager.Get(Convert.ToInt32(commandId));
}
private bool IsClientMessage(LogEventInfo logEvent, CommandModel command)
{
if (command == null || !command.Body.SendUpdatesToClient)
{
11 years ago
return false;
}
11 years ago
return logEvent.Properties.ContainsKey("Status");
}
private bool ReentryPreventionCheck()
{
var reentryLock = MappedDiagnosticsContext.Get(REENTRY_LOCK);
var commandId = MappedDiagnosticsContext.Get("CommandId");
if (reentryLock.IsNullOrWhiteSpace() || reentryLock != commandId)
{
MappedDiagnosticsContext.Set(REENTRY_LOCK, MappedDiagnosticsContext.Get("CommandId"));
return true;
}
return false;
}
11 years ago
public void Handle(ApplicationStartedEvent message)
{
11 years ago
_rule = new LoggingRule("*", LogLevel.Trace, this);
LogManager.Configuration.AddTarget("ProgressMessagingLogger", this);
LogManager.Configuration.LoggingRules.Add(_rule);
LogManager.ReconfigExistingLoggers();
}
}
}