c#在Mongo中使用NLog

时间:2018-12-14 14:26:43

标签: c# .net mongodb logging nlog

我将使用NLog和MongoDB记录我的数据。我这样配置NLog.config:

<extensions>
  <add assembly="NLog.Mongo"/>
</extensions>
...
 <target xsi:type="Mongo"
        name="mongo"
        includeDefaults="false"
        connectionString="mongodb://localhost"
        collectionName="myCollection"
        databaseName="logs"
        cappedCollectionSize="26214400">
  <field name="_id" layout="${Id}"/>
  <field name="ts" layout="${Timestamp}" bsonType="DateTime"/>
  <field name="cap" layout="${ApplicationCaller}" />
</target>

但是我如何在日志中传递值ID,时间戳,ApplicationCaller? 我尝试以下代码:

public void LogExceptionOnMongo(string callIdentifier, string applicationCaller)
{
     var _myLogger = LogManager.GetLogger("mongo");
     var logEventInfo = new LogEventInfo(LogLevel.Fatal, "", "Exception");
     logEventInfo.Properties["CallIdentifier"] = callIdentifier;
     logEventInfo.Properties["TimeStamp"] = DateTime.UtcNow;
     logEventInfo.Properties["ApplicationCaller"] = applicationCaller;

     _myLogger.Log(logEventInfo);
}

和此配置:

<target xsi:type="Mongo"
        name="mongo"
        includeDefaults="false"
        connectionString="mongodb://localhost"
        collectionName="myCollection"
        databaseName="logs"
        cappedCollectionSize="26214400">
  <field name="_id" layout="${event-properties:item=CallIdentifier}"/>
  <field name="ts" layout="${event-properties:item=TimeStamp}" bsonType="DateTimeUtc"/>
  <field name="cap" layout="${event-properties:item=ApplicationCaller}" />
</target>

但是我在mongo中获得了此日志(我不会圈出数据):

enter image description here

任何人都可以帮助我吗?谢谢你,抱歉我的英语水平

2 个答案:

答案 0 :(得分:2)

必须对此进行代码更改才能适应。有关更多信息,请参见Issue

现在可以配置新属性includeEventProperties

<target xsi:type="Mongo"
        name="mongo"
        includeDefaults="false"
        includeEventProperties="false"
        connectionString="mongodb://localhost"
        collectionName="myCollection"
        databaseName="logs"
        cappedCollectionSize="26214400">
  <field name="_id" layout="${event-properties:item=CallIdentifier}"/>
  <field name="ts" layout="${event-properties:item=TimeStamp}" bsonType="DateTimeUtc"/>
  <field name="cap" layout="${event-properties:item=ApplicationCaller}" />
</target>

只需使用ver。来自nuget的4.6.0.68:https://www.nuget.org/packages/NLog.Mongo

答案 1 :(得分:0)

今天早上,我尝试使用新版本的库,这是新的配置:

   <target xsi:type="Mongo"
        name="mongo"
        includeDefaults="false"
        connectionString="mongodb://localhost"
        collectionName="myCollection"
        databaseName="logs"
        cappedCollectionSize="26214400"
        includeEventProperties="false">
  <field name="_id" layout="${event-properties:item=CallIdentifier}"/>
  <field name="ts" layout="${event-properties:item=TimeStamp}" bsonType="DateTime"/>
  <field name="cap" layout="${event-properties:item=ApplicationCaller}" />
</target>

具有新标签 includeEventProperties = false ,并且其新属性位于类MongoTarget中,并且可以正常工作。结果如下: enter image description here 非常感谢,干得好