Nlog: Write Log To DataBase In .Net Standard 2.0

Created on 24 Dec 2017  路  15Comments  路  Source: NLog/NLog

Question

Hi! Dear:
I having a issue with nlog in .net standard 2.0 when write logs to a sqlserver datatable.
The table structure is a already,but it throw an exception.

NLog version:5.0.0-beta11

System.Data.SqlClient:4.4.2

Platform: .Net Standard 2.0

Current NLog config

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true" throwExceptions="true">
  <targets>
    <target name="log4file" xsi:type="File" fileName="${basedir}/Logs/${level}/${shortdate}.txt"
           layout="${callsite}|${longdate}|${level}|${message}" />

    <target name="log4database" xsi:type="Database" dbProvider="System.Data.SqlClient" >
      <connectionString>
        Server=.\\SQLEXPRESS;Initial Catalog=Light;User ID=sa;Password=sasa;
      </connectionString>
      <commandText>
        INSERT INTO dbo.NLogDetails
        (CreateDate, Message, Level, Logger) 
        VALUES(getdate(), @message, @level, @logger)
      </commandText>
      <parameter name="@level" layout="${level}" />
      <parameter name="@message" layout="${message}" />
      <parameter name="@logger" layout="${logger}" />
    </target>
  </targets>

  <rules>
    <logger name="*" levels="Trace,Error" writeTo="log4database" />
    <logger name="*" level="Info" writeTo="log4file" />
  </rules>
</nlog>

Exception
Message:
Could not load type 'System.Data.SqlClient' from assembly 'NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c'.
StackTrace:
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError)
at NLog.Targets.DatabaseTarget.SetConnectionType()
at NLog.Targets.DatabaseTarget.InitializeTarget()
at NLog.Targets.Target.Initialize(LoggingConfiguration configuration)
at NLog.Targets.Target.NLog.Internal.ISupportsInitialize.Initialize(LoggingConfiguration configuration)
at NLog.Config.LoggingConfiguration.InitializeAll()
at NLog.LogFactory.set_Configuration(LoggingConfiguration value)
at Light.Common.NLogManager..cctor() in C:\Project\VSProject\Light\Light.Common\NLogManager.cs:line 20

Thanks!

.NET core database-target documentation question

Most helpful comment

@faisaliyk & @shiroi-tora & @faisaliyk Apparently one should just remove dbProvider="System.Data.SqlClient" when using NetCore with System.Data.SqlClient.

https://stackoverflow.com/questions/48181439/nlog-database-target-for-net-core-2-0

All 15 comments

You need to add the System.Data.SqlClient nuget package to your program. Is it really added?

PS recommended to update to nlog 4.5 rc

@304NotModified I update nlog to 4.5.0-rc03 in standard 2.0 ,and add System.Data.SqlClient to asp.net core webapi,but still throw the same exception:
TypeLoadException: Could not load type 'System.Data.SqlClient' from assembly 'NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c'.

PS:log to file going well

I am also getting this issue. System.Data.SqlClient is present in .csporj, log to file working well. But log to database is getting this error all the time.

could you try version 4.4.0 of System.Data.SqlClient OR add an <bindingRedirect> in the .config?

Hi. @IMJacky and @304NotModified I am seeing the same issue. Logging to file with NLog works, but I can't seem to log in the DB. I am getting the same error code. Any thoughts for a work around?

@faisaliyk & @shiroi-tora & @faisaliyk Apparently one should just remove dbProvider="System.Data.SqlClient" when using NetCore with System.Data.SqlClient.

https://stackoverflow.com/questions/48181439/nlog-database-target-for-net-core-2-0

@IMJacky

your nlog.config should resemble as mentioned here - https://github.com/hatimjohar/NLogToDatabase/blob/master/NlogToDatabase/NlogToDatabase/nlog.config

Points to Note:

  1. Add extension tag
  2. your connection string should not have double back slashes (\), instead it should have one
  3. Remove dbProvider="System.Data.SqlClient" from your target tag

A working sample is available at git repository https://github.com/hatimjohar/NLogToDatabase

@hatimjohar could please add this to the wiki? https://github.com/NLog/NLog/wiki/Database-Target

Thx in advance!

@snakefoot good job锛宨t's work!!! tks~~ @304NotModified you maybe should change the docs:)

@IMJacky feel free to add/edit, it's a wiki!

@faisaliyk & @shiroi-tora & @faisaliyk & @hatimjohar & @IMJacky Have now made a small fix for NetCore only, so it will correctly recognize dbProvider="System.Data.SqlClient". See #2518

I am now running into this same problem, but the solution does not work for me; I don't have dbProvider in my config, nor do I see that library anyway. Regardless, you shouldn't be using System.Data.SqlClient at all anymore now that Microsoft.Data.SqlClient is available

`2020-02-03 15:15:51.9719 Error Database Target[database]: Error initializing target Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Data.SqlClient, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

File name: 'System.Data.SqlClient, Culture=neutral, PublicKeyToken=null'

at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)

at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)

at System.Reflection.Assembly.Load(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)

at System.Reflection.Assembly.Load(AssemblyName assemblyRef)

at NLog.Targets.DatabaseTarget.SetConnectionType()

at NLog.Targets.DatabaseTarget.InitializeTarget()

at NLog.Targets.Target.Initialize(LoggingConfiguration configuration)

`

@unionthugface You need to add nuget-package https://www.nuget.org/packages/System.Data.SqlClient/ to your project. Else it cannot be loaded.

Please don't wake up old issues with your random problems. Instead create new issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ranjan-2209 picture ranjan-2209  路  3Comments

FaMouZx3 picture FaMouZx3  路  3Comments

Sam13 picture Sam13  路  3Comments

Rapiiidooo picture Rapiiidooo  路  3Comments

carkov1990 picture carkov1990  路  3Comments