jam*_*tou 5 c# sql-server datetime nlog nlog-configuration
我试图使用NLog 2将一些审计信息记录到SQL Server 2008表.为了能够将参数传递给SQL插入查询,我使用的是LogEventInfo和事件上下文布局呈现器.
日志记录本身有效,但日期时间仅以第二精度存储.我希望能够以毫秒精度存储,但没有找到任何能告诉我如何执行此操作的内容.
这是我记录事件的C#代码:
private void LogMessage(DateTime requestDateTime)
{
LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", "Pass my custom value");
theEvent.Properties["RequestDate"] = requestDateTime;
}
Run Code Online (Sandbox Code Playgroud)
这是我在NLog.config配置中的目标:
<target xsi:type="Database"
name="SqlLog"
dbProvider="sqlserver"
connectionString="server=localhost;database=Test;integrated security=sspi">
<commandText>
INSERT [dbo].[ApiLog]
(
[ServerName], [RequestDate]
)
VALUES (@ServerName, @RequestDate);
</commandText>
<parameter name="@ServerName" layout="${machinename}"/>
<parameter name="@RequestDate" layout="${event-context:item=RequestDate}"/>
</target>
Run Code Online (Sandbox Code Playgroud)
有一个我发现使用的解决方法,theEvent.Properties["RequestDate"] = requestDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")但我不想这样做,因为那样你可能会遇到日期时间格式和文化问题.
有谁知道我可以在NLog.config中使用config更改精度的方法?
看起来 EventContextLayoutRenderer 使用的Convert.ToString将失去您正在寻找的精度:
public class EventContextLayoutRenderer : LayoutRenderer
{
//....
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
object value;
if (logEvent.Properties.TryGetValue(this.Item, out value))
{
builder.Append(Convert.ToString(value, CultureInfo.InvariantCulture));
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您可能知道的那样(我不确定它对您的情况是否有帮助),但是有一个日期布局,您可以在其中指定格式和/或 LongDate 布局,它将提供类似的内容2014-01-01 12:12:12.1234
编辑
对于它的价值,您可以非常轻松地添加客户布局渲染器
[LayoutRenderer("event-context-dateTime")]
public class DateTimeContextLayoutRenderer : EventContextLayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
object value;
if (logEvent.Properties.TryGetValue(this.Item, out value))
{
//Your code here
}
}
}
Run Code Online (Sandbox Code Playgroud)
并且在你的配置中
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<add assembly="YourAssembly"/>
</extensions>
<targets>
<target xsi:type="File" name="file" fileName="c:\temp\NlogLayout.txt"
layout="${longdate} ${event-context-dateTime:item=RequestDate}" />
...
</nlog>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1818 次 |
| 最近记录: |