C# 如何配置 NLog 以写入数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17188478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:47:13  来源:igfitidea点击:

How do I configure NLog to write to a database?

c#databasenlog

提问by Captain_Custard

I'm trying to get NLog to write to a database, however with my current code it throws an exception when I attempt to debug, the exception is: The type initializer for 'NotifyIcon.Program' threw an exception.

我正在尝试让 NLog 写入数据库,但是使用我当前的代码在尝试调试时抛出异常,异常是:“NotifyIcon.Program”的类型初始值设定项抛出异常。

my NLog configuration file code is below, as this seems to be causing the issue as it's the only code I've changed.

我的 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>

any and all help would be greatly appreciated =]

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

采纳答案by Brad Bruce

You seem to be missing the parameters that are to be inserted.

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

See the examples at http://justinpdavis.blogspot.com/2010/04/logging-to-database-with-nlog.html

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

The nLog web page doesn't make it very clear that these are required, but if you squint your eyes and read https://github.com/nlog/NLog/wiki/Database-targetyou should find that they are required.

nLog 网页并没有明确说明这些是必需的,但是如果您眯着眼睛阅读https://github.com/nlog/NLog/wiki/Database-target,您应该会发现它们是必需的。

回答by automatic

It looks your insert string is not in the right format? You are missing () around the parameters list.

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

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) "

回答by WtFudgE

U also wrote 2 targets. And also a lot of attributes that u don't need to set. Should just be:

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

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

Something like this. Easy no? :)

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

回答by Julian

A simple example,

一个简单的例子,

Config:

配置:

<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>

Note, NLog 4.6 has also support for DbType - See https://nlog-project.org/2019/03/20/nlog-4-6-is-live.html

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