1

So I set up NLog config file supposedly correct (did the same thing i did on a working project) however in this project it fails for some reason the database Logs table is empty. Can somone tell me what may cause the issue?

Heres the code

Controller

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>

And connection string in 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>
Raf
  • 85
  • 1
  • 1
  • 8
  • You cannot use Entity Framework's connection string. See [my answer](https://stackoverflow.com/a/45202964/296861). – Win Jul 20 '17 at 13:07
  • Where should i derive the connection string from? I don't think i have a startup.cs in my project, i also tried setting connectionString tag to the one thats inside my web.config but that didn't work. – Raf Jul 20 '17 at 13:15
  • ASP.NET Core doesn't use web.config except for hosting in IIS. Place the connection string inside `appsettings.json`. – Win Jul 20 '17 at 13:16
  • Oh dang it, i feel stupid, my project is a regular asp.net web application not asp.net core – Raf Jul 20 '17 at 13:21
  • I see. Anyhow, you can place `internalLogLevel="Warn" internalLogFile="C:\temp\internal-nlog.txt"` to see the nlog error. – Win Jul 20 '17 at 13:22
  • Ok so i get a `2017-07-20 17:53:43.5138 Error Error initializing target 'Database Target[dbl_wrapped]'. Exception: System.ArgumentException: Unable to find the requested .Net Framework Data Provider.It may not be installed. in System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName) in NLog.Targets.DatabaseTarget.InitializeTarget() in NLog.Targets.Target.Initialize(LoggingConfiguration configuration)` exception, also i am using visual studio 2017 and also have 2013 installed on my pc could it cause a problem? – Raf Jul 20 '17 at 13:58
  • Another thing is that my old project works on both 2017 and 2013, so the problem is in the new project . – Raf Jul 20 '17 at 14:07
  • Please make sure you have correct provider name `providerName="System.Data.SqlClient"`, if you use SQL Server. Not `providerName="System.Data.EntityClient"`. ***Again, you cannot use Entity Frameworks connection string for NLog.*** – Win Jul 20 '17 at 14:10
  • OK i now seem to understand it, the connection provider tag for the connection string in web.config is System.Data.EntityClient therefore it doesn't work with NLog, am i right? If so what can i do to get around this? – Raf Jul 20 '17 at 14:23
  • I updated my answer. – Win Jul 20 '17 at 14:30

2 Answers2

2

Easiest way is to create a variable inside nlog file, and assign the connection string value from 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");
        ...
    }
}

}

Update

Based on comment, you are using ASP.NET MVC. You cannot use Entity Framework Connection string for NLog. Instead, you will need to have a separate connection string like this -

<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"/>
Win
  • 61,100
  • 13
  • 102
  • 181
0

The problem turned out to be the connection string provider which is System.Data.EntityClient which is currently not supported by NLog Found here

Raf
  • 85
  • 1
  • 1
  • 8
  • NLog 4.5 adds support for Entity Framework ConnectionString, so they can be referenced directly. See https://github.com/NLog/NLog/pull/2510 – Rolf Kristensen Feb 24 '19 at 10:04