使用数据库上的NLog自定义日志记录

时间:2020-04-15 13:55:17

标签: c# database nlog

我的NLog有问题。根据{{​​3}}说

如果要自定义布局属性(NLog称其为布局渲染器),则可以使用EventProperties布局渲染器。

我写了一些配置:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="on" internalLogFile="c:\temp\nlog-internal.log">

<targets>
  <!-- database target  -->
  <target name="databaseauthentication"
          xsi:type="Database"
          connectionString="Data Source = [....]; Initial Catalog = [....]; User Id = [....]; Password = [....]"
          commandText="exec dbo.InsertAuthentication
                        @company,
                        @firstname,
                        @lastname,
                        @ip,
                        @pcname,
                        @additionalInfo">
    <parameter name="@company" layout="${event-properties:item=companyValue}" />
    <parameter name="@firstname" layout="${event-properties:item=firstnameValue}" />
    <parameter name="@lastname" layout="${event-properties:item=lastnameValue}" />
    <parameter name="@ip" layout="${event-properties:item=ipValue}" />
    <parameter name="@pcname" layout="${event-properties:item=pcnameValue}" />
    <parameter name="@additionalInfo" layout="${event-properties:item=additionalInfoValue}" />
  </target>
</targets>


<rules>
   <logger levels="Info" name="asyncdatabaseauthenticationLogger" writeTo="asyncdatabaseauthentication"/>
   <logger levels="Info" name="databaseauthenticationLogger" writeTo="databaseauthentication"/>
</rules>
</nlog>

并像这样使用它:

 public static void SendLogin()
        {

            var eventInfo = new LogEventInfo(LogLevel.Info, databaseAuthenticateLogger.Name, "Message");
            eventInfo.Properties["firstnameValue"] = "My Fist Name;
            eventInfo.Properties["lastnameValue"] = "My Last Name";
            eventInfo.Properties["companyValue"] = "My Company";
            eventInfo.Properties["ipValue"] = "IP";
            eventInfo.Properties["pcnameValue"] = "PC Name";
            eventInfo.Properties["additionalInfoValue"] = "Login";
            databaseAuthenticateLogger.Log(eventInfo);
        }

但是此代码不起作用。谁能告诉我我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

上面的代码是正确的,但是我们需要在c#代码中添加此部分:

knownFruits = {banana, melon, apple, pineapple, guava}
knownAnimals = {dog, cat, bird, leopard, shark}
fruits = []
animals = []

for row in x:
    for elem in row:
        if elem in fruits:
            fruits.append(elem)
        elif elem in animals:
            animals.append(elem)
#etc.

一切正常。

相关问题