如何配置NLog写入数据库?

时间:2013-06-19 10:05:35

标签: c# database nlog

我正在尝试让NLog写入数据库,但是当我尝试调试时,我的当前代码会引发异常,例外是:'NotifyIcon.Program'的类型初始化程序引发异常。

我的NLog配置文件代码如下,因为这似乎是导致问题,因为它是我改变的唯一代码。

<?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" autoReload="true">

  <!-- 
  See http://nlog-project.org/wiki/Configuration_file 
  for information on customizing logging rules and outputs.
   -->
  <targets>
    <!-- add your targets here -->

    <target name="database" xsi:type="Database" />
    <target xsi:type="Database"
          name="String"
          dbUserName="Layout"
          dbProvider="sqlserver"
          useTransactions="false"
          connectionStringName="String"
          connectionString="Data Source=AC-02\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"
          keepConnection="true"
          dbDatabase="Layout"
          dbPassword="Layout"
          dbHost="Layout"
          installConnectionString="Layout"
          commandText="INSERT INTO Logs (Machine_Name, Username, Logon_Time, Screensaver_On, Screensaver_Off, Logoff_Time, Program_Start) Values @MachineName, @Username, @LogonTime, @Screensaver_On, @Screensaver_Off, @LogoffTime, @ProgramStart "/>

  </targets>

  <rules>

    <logger name="*" minlevel="Trace" writeTo="database" />

  </rules>
</nlog>

任何和所有帮助将不胜感激=]

4 个答案:

答案 0 :(得分:13)

您似乎缺少要插入的参数。

请参阅http://justinpdavis.blogspot.com/2010/04/logging-to-database-with-nlog.html

上的示例

nLog网页并不十分清楚这些是必需的,但是如果你眯着眼睛看了https://github.com/nlog/NLog/wiki/Database-target,你会发现它们是必需的。

答案 1 :(得分:1)

看起来您的插入字符串格式不正确?你在参数列表周围缺少()。

commandText="INSERT INTO Logs (Machine_Name, Username, Logon_Time, Screensaver_On, Screensaver_Off, Logoff_Time, Program_Start) Values (@MachineName, @Username, @LogonTime, @Screensaver_On, @Screensaver_Off, @LogoffTime, @ProgramStart) "

答案 2 :(得分:1)

你还写了2个目标。还有很多你不需要设置的属性。应该只是:

<target name="DbLog" xsi:type="Database" connectionString="YourConStr" 
        commandText="insert into [blablablabal] (Col1) values (@val1)">
  <parameter name="@val1" layout="${level}" /></target>

像这样的东西。容易没? :)

答案 3 :(得分:1)

一个简单的例子,

配置:

<target type="Database" name="database" connectionstring="Server=localhost;Database=NLog;Trusted_Connection=True;">
  <commandText>
    INSERT INTO NLogEntries ([Origin], [Message], [LogLevel],[CreatedOn],[OrderId]) VALUES (@Origin,@Message,@LogLevel,@Date, @OrderId);
  </commandText>
  <parameter name="@Date" layout="${date}" dbType="DbType.Date"/>
  <parameter name="@Origin" layout="${callsite}"/>
  <parameter name="@LogLevel" layout="${level}"/>
  <parameter name="@message" layout="${message}"/>
  <parameter name="@OrderId" layout="${event-properties:MyOrderId}" dbType="DbType.Int32"/> <!-- custom field! Note also the DB Type. Using Logger.WithProperty -->
</target>

注意,NLog 4.6还支持DbType-请参见https://nlog-project.org/2019/03/20/nlog-4-6-is-live.html