【发布时间】:2015-01-21 04:50:27
【问题描述】:
我编写了一个 NLog 目标,旨在获取 NLog LogEventInfo 并将其写入 Azure 的 API 服务。我无法为记录器编写单元测试,因为我不知道如何拦截记录到 APIServices.Log.Trace 的消息。
这是目标定义:
namespace Ariel.Mobile.Logging
{
using System.Collections;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Tracing;
using Ariel.Library;
using Microsoft.WindowsAzure.Mobile.Service;
using Ninject;
using NLog;
using NLog.Targets;
/// <summary>
/// Class to be used with NLog to write error and debug data to Azure for storage.
/// </summary>
[Target("Azure")]
public class AzureTarget : Target
{
#region Fields
/// <summary>
/// Defines the mappings between NLog and Azure levels.
/// </summary>
private static readonly IDictionary<LogLevel, TraceLevel> LevelMap =
new Dictionary<LogLevel, TraceLevel>
{
{ LogLevel.Trace, TraceLevel.Debug },
{ LogLevel.Debug, TraceLevel.Debug },
{ LogLevel.Info, TraceLevel.Info },
{ LogLevel.Warn, TraceLevel.Warn },
{ LogLevel.Error, TraceLevel.Error },
{ LogLevel.Fatal, TraceLevel.Fatal }
};
/// <summary>
/// Gets or sets the Azure service to which messages will be sent.
/// </summary>
private readonly ApiServices services;
#endregion
public AzureTarget()
{
services = new ApiServices(ServiceConfig.Config);
}
#region Methods
/// <summary>
/// Method accepting NLog logging events to be transmitted to Azure.
/// </summary>
/// <param name="logEvent">The NLog event which needs to be persisted.
/// </param>
protected override void Write(LogEventInfo logEvent)
{
this.services.Log.Trace(LevelMap[logEvent.Level], logEvent.Message, logEvent.Exception);
}
#endregion
}
}
如何在单元测试中截获记录到 APIServices.Log.Trace 的消息?
【问题讨论】: