繁体   English   中英

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

[英]Custom logging with NLog on database

我对 NLog 有一些问题。 根据这里

如果您想要自定义布局属性(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# 代码中添加这部分:

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

一切都很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM