我想使用 NLog 记录到 RavenDb 数据库。显然没有现有的 NLog 目标(根据this和搜索),所以我正在尝试编写自己的。我一直与 RavenDb 客户端自己的 NLog 配置发生冲突,我不知道如何解决这个问题。这是我的目标:
namespace NLog.RavenDb
{
class LogEntry
{
public string Id { get; set; }
public Exception Exception { get; set; }
public string LogLevel { get; set; }
public StackTrace StackTrace { get; set; }
public DateTimeOffset TimeStamp { get; set; }
public string Message { get; set; }
}
public class RavenDbTarget : NLog.Targets.TargetWithLayout
{
public static IDocumentStore Store { get; set; }
protected override void Write(LogEventInfo logEvent)
{
if (Store == null)
{
const string noStoreWarning = "No Document Store set for the RavenDb Log target";
Debug.WriteLine(noStoreWarning);
return;
}
LogEntry entry = new LogEntry
{
Exception = logEvent.Exception,
LogLevel = logEvent.Level.Name,
Message = logEvent.FormattedMessage,
StackTrace = logEvent.StackTrace,
TimeStamp = new DateTimeOffset(logEvent.TimeStamp)
};
using (var session = Store.OpenSession())
{
session.Store(entry);
session.SaveChanges();
}
}
}
}
下面是我如何让它与 SimpleConfigurator 一起工作:
RavenDbTarget.Store = new DocumentStore { Url = "http://localhost:8080/" };
RavenDbTarget.Store.Initialize();
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(new RavenDbTarget());
Logger logger = NLog.LogManager.GetLogger("Any");
logger.Info("Hi");
但是,RavenDb 也使用 NLog.config,因此当我将 Target 的引用放在那里时,它会在 Store.Initialize() 处引发异常。这是我在 NLog.config 中尝试的内容(NLog.RavenDb 是包含 RavenDb 目标的库项目的名称):
<?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">
<extensions>
<add assembly="Nlog.RavenDb"/>
</extensions>
<targets>
<target xsi:type="NLog.RavenDb.RavenDbTarget" name="Raven"/>
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger minlevel="Trace" name="Any" writeTo="Raven" />
</rules>
</nlog>
如何让我的 NLog.config 文件与 RavenDb 的使用配合得很好?