【问题标题】:Custom logging with NLog on database在数据库上使用 NLog 自定义日志记录
【发布时间】:2020-04-15 13:55:17
【问题描述】:

我对 NLog 有一些问题。据here说的

如果您想要自定义布局属性(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);
        }

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

【问题讨论】:

标签: c# database nlog


【解决方案1】:

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

static Logger databaseAuthenticateLogger = LogManager.GetLogger("databaseauthenticationLogger");
static Logger asyncdatabaseAuthenticateLogger = LogManager.GetLogger("asyncdatabaseauthenticationLogger");

一切正常。

【讨论】:

  • 你也可以改成&lt;logger levels="Info" name="*" writeTo="databaseauthentication"/&gt;(这样任何一个logger都会到达数据库)
猜你喜欢
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 2016-05-02
相关资源
最近更新 更多