[英]NLog is not logging into the database when its configured to log from code
我有以下控制台应用程序,它使用 NLog 使用编程配置实现日志记录。 目前,它当前没有登录数据库,并且在运行时也没有抛出任何异常。 有人可以告诉我背后的原因吗?
using NLog;
using NLog.Config;
using NLog.Targets;
using System;
namespace Test.Logger
{
class Program
{
static void Main(string[] args)
{
var logConfig = new LoggingConfiguration();
//dbtarget 2
var dbTarget2 = new DatabaseTarget();
dbTarget2.ConnectionString = "SomeConnectionString";
dbTarget2.CommandText = @"INSERT INTO [dbo].[LogAppDetail]
([LogAppIS]
,[LogAppId]
,[DN]
,[DV])
VALUES
(@LogAppIS
,@LogAppId
,@DN
,@DV)";
dbTarget2.Parameters.Add(new DatabaseParameterInfo("@LogAppIS", new NLog.Layouts.SimpleLayout("${event-properties:LogAppIS}")));
dbTarget2.Parameters.Add(new DatabaseParameterInfo("@LogAppId", new NLog.Layouts.SimpleLayout("${event-properties:LogAppId}")));
dbTarget2.Parameters.Add(new DatabaseParameterInfo("@DN", new NLog.Layouts.SimpleLayout("${event-properties:DN}")));
dbTarget2.Parameters.Add(new DatabaseParameterInfo("@DV", new NLog.Layouts.SimpleLayout("${event-properties:DV}")));
logConfig.AddTarget("dbTarget2", dbTarget2);
// add rules
var rule2 = new LoggingRule("LogAppDetail", LogLevel.Trace, dbTarget2);
logConfig.LoggingRules.Add(rule2);
LogManager.Configuration = logConfig;
LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", "Pass my custom value");
theEvent.Properties["LogAppIS"] = "12345698";
theEvent.Properties["LogAppId"] = "1235";
theEvent.Properties["DN"] = "DN";
theEvent.Properties["DV"] = "DV";
var log = NLog.LogManager.GetLogger("LogAppDetail");
log.Log(theEvent);
}
}
}
我弄清楚了上面的代码没有登录到数据库的原因。 我的.net核心项目中缺少system.data.sqlclient软件包。 我通过在应用程序中遵循以下异常来解决这个问题。
LogManager.ThrowExceptions = true;
LogManager.ThrowConfigExceptions = true;
对于仍在为此苦苦挣扎的任何人,如此处所述,为了从 NLog 5.0 和更新版本中进行这项工作,您必须包含 nuget package Nlog.Database
所以,这应该有魔力:
<PackageReference Include="NLog.Database" Version="5.0.2" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.