无法让NLog工作

时间:2017-07-19 23:52:14

标签: c# asp.net nlog

所以我设置NLog配置文件应该是正确的(我在一个工作项目上做了同样的事情)然而在这个项目中由于某种原因它失败了数据库Logs表是空的。可以告诉我可能导致这个问题的原因吗?

继承代码

控制器

public class HomeController : Controller    
{ 
       private ShopModel db = new ShopModel();
       private static Logger logger = LogManager.GetLogger("dbloger");
       public ActionResult Index()
        {   
            logger.Info("Test");
            return View(db.Users);
        }
}

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

    <target name="dbl" xsi:type="Database" connectionStringName="ShopModel"
           dbProvider="System.Data.EntityClient"
           commandText=" INSERT INTO Logs ([Usrname] ,[Log], [Date]) VALUES (@Email,@Message, @Date);" >

      <parameter name="@Message" layout="${message}"/>
      <parameter name="@Date" layout="${longdate}" />
      <parameter name="@Email" layout="${gdc:Email}" />

    </target >
  </targets>

  <rules>

    <logger name="*" minlevel="Trace" writeTo="dbl" />
  </rules>
</nlog>

web.config中的连接字符串

<connectionStrings>

 <add name="ShopModel" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Shopdb.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

</connectionStrings>

2 个答案:

答案 0 :(得分:1)

最简单的方法是在nlog文件中创建一个变量,并从 Startup.cs 中分配连接字符串值。

<connectionString>${var:connectionString}</connectionString>

nlog.config

<?xml version="1.0" encoding="utf-8" ?>

<!--
  NOTE: Use this to log internal error, if you have issue configuring NLog.

  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="C:\temp\internal-nlog.txt">
-->

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true">

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <targets>
    <target xsi:type="Null" name="blackhole" />
    <target name="database" xsi:type="Database">
      <connectionString>${var:connectionString}</connectionString>
      <!-- 
          Script for creating the dbo.Log table.

          SET ANSI_NULLS ON
          GO
          SET QUOTED_IDENTIFIER ON
          GO
          CREATE TABLE [dbo].[Logs](
              [Id] [int] IDENTITY(1,1) NOT NULL,
              [Application] [nvarchar](50) NOT NULL,
              [Logged] [datetime] NOT NULL,
              [Level] [nvarchar](50) NOT NULL,
              [Action] [nvarchar](50) NULL,
              [Controller] [nvarchar](50) NULL,
              [Identity] [nvarchar](50) NULL,
              [Referrer] [nvarchar](250) NULL,
              [UserAgent] [nvarchar](250) NULL,
              [Url] [nvarchar](500) NULL,
              [Message] [nvarchar](max) NOT NULL,
              [Logger] [nvarchar](250) NULL,
              [Callsite] [nvarchar](max) NULL,
              [Exception] [nvarchar](max) NULL,
           CONSTRAINT [PK_dbo.Logs] PRIMARY KEY CLUSTERED 
          (
              [Id] 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]

          GO
        -->
      <commandText>
        INSERT INTO dbo.Logs (Application,Logged,[Level],Action,Controller,[Identity],Referrer,UserAgent,Url,Message,Logger,Callsite,Exception)
        VALUES (@Application,@Logged,@Level,@Action,@Controller,@Identity,@Referrer,@UserAgent,@Url,@Message,@Logger,@Callsite,@Exception);
      </commandText>
      <parameter name="@Application" layout="ASP" />
      <parameter name="@Logged" layout="${date}" />
      <parameter name="@Level" layout="${level}" />
      <parameter name="@Action" layout="${aspnet-MVC-Action}" />
      <parameter name="@Controller" layout="${aspnet-MVC-Controller}" />
      <parameter name="@Identity" layout="${aspnet-User-Identity}" />
      <parameter name="@Referrer" layout="${aspnet-Request-Referrer}" />
      <parameter name="@UserAgent" layout="${aspnet-Request-UserAgent}" />
      <parameter name="@Url" layout="${aspnet-Request-Url}" />
      <parameter name="@Message" layout="${message}" />
      <parameter name="@Logger" layout="${logger}" />
      <parameter name="@CallSite" layout="${callsite:filename=true}" />
      <parameter name="@Exception" layout="${exception:tostring}" />
    </target>
  </targets>

  <rules>
    <!-- Skip Microsoft logs, and log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="database" />
  </rules>
</nlog>

Startup.cs

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        env.ConfigureNLog("nlog.config");
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...
        loggerFactory.AddNLog();
        app.AddNLogWeb();
        LogManager.Configuration.Variables["connectionString"] = 
            Configuration.GetConnectionString("DefaultConnection");
        ...
    }
}

}

更新

根据评论,您正在使用ASP.NET MVC。您不能将实体框架连接字符串用于NLog。相反,您需要有一个单独的连接字符串 -

<add name="CONNECTION_STRING_NAME_FOR_NLOG" 
         connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Shopdb.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework" 
         providerName="System.Data.SqlClient"/>

答案 1 :(得分:0)

问题原来是连接字符串提供程序,System.Data.EntityClient目前NLog不支持 Found here