背景

我正在使用.net 4.0控制台应用程序(使用Visual Studio 2012编写)的NLog版本2.0.1(我认为它是最新版本)。

该应用程序很简单:

namespace NLogConsoleApplication
{
    class Program
    {
        static void Main()
        {
            NLog.LogManager.GetCurrentClassLogger().Info("A testypoos");
        }
    }
}

我有以下NLog.config文件:
<?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"
      throwExceptions="true"
      autoReload="true"
      internalLogFile="C:\Users\Public\nlog.txt"
      internalLogLevel="Debug">
  <targets>
    <target type="Database" name="tl" >
        <connectionString>data source=.\;initial catalog=NLogTest;integrated security=false;User ID=iwillnotfallforthisone;Password=goodtry</connectionString>
        <commandText>
          insert into TestLog2 ([LogDate], [LogLevel], [LogMessage]) values (@logDate, @logLevel, @logMessage);
        </commandText>
        <parameter name="@logDate" layout="${date}"/>
        <parameter name="@logLevel" layout="${level}"/>
        <parameter name="@logMessage" layout="${message}"/>
    </target>
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="tl" />
  </rules>
</nlog>

这样创建TestLog2表:
CREATE TABLE [dbo].[TestLog2](
    [LogId] [bigint] IDENTITY(1,1) NOT NULL,
    [LogDate] [datetime] NOT NULL,
    [LogLevel] [nvarchar](20) NOT NULL,
    [LogMessage] [nvarchar](max) NOT NULL,
 CONSTRAINT [PK_TestLog2] PRIMARY KEY CLUSTERED
(
    [LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

当我运行该应用程序时,出现此异常(我将Google翻译为它-希望可以理解):
Unhandled Exception: NLog.NLogRuntimeException: Exception occurred in NLog --- > System.Data.SqlClient.SqlException:During the conversion of a nvarchar data type to a datetime data type, the value is out of range.
The statement has been terminated.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
   at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
   at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)
   --- End of inner exception stack trace ---
   at NLog.LoggerImpl.<>c__DisplayClass1.<Write>b__0(Exception ex)
   at NLog.Internal.SingleCallContinuation.Function(Exception exception)
   at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)
   at NLog.Targets.Target.WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
   at NLog.LoggerImpl.WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
   at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
   at NLog.Logger.Info(String message)
   at NLogConsoleApplication.Program.Main() in c:\xxxxxxx\Program.cs:Line 7.

如果我将LogDate列更改为nvarchar,则可以正常工作,但是我真的不希望该列为字符串,因为我希望能够基于日期对表进行排序和搜索。

笔记
  • 我在连接到德语版本的SQL Sever 2012的德语版本的Windows Server 2008 R2标准上运行此文件。
  • 如果我连接到英语SQL Server 2012实例,则可以正常工作。
  • 我检查了nlog.txt文件,那里似乎没有更多信息(只是相同的异常跟踪)

  • 问题

    也许这只是NLog中的错误,或者只是我可以更改的配置,或者有一个聪明的解决方法,所以有人知道我将如何让NLog在时间戳中将DateTime放入数据库中吗?

    最佳答案

    我猜想NLog的datetime的格式是MM/dd/yyyy,而德国SQL Server则期望dd/MM/yyyy。您可以使用以下方式显式指定日期格式:

    <parameter name="@logDate" layout="${date:format=yyyy-MM-dd}"/>
    

    SQL Server应该能够解析日期并适本地插入日期,而不考虑期望MM/dddd/MM的语言环境。

    A similar question

    NLog Documentation

    关于c# - NLog-数据库配置-德语SQL Server上的异常-任何想法如何解决?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17163679/

    10-13 09:40