简体   繁体   中英

NLog | logging to database is not working asp.net core Blazor Server

I'm trying to add nlog to log to the file system (completed and working) and the database (not working).

I've tried everything with many posts and I can't seem to get the right configuration to work.

Here is my setup:

<?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"
      internalLogLevel="Info"
      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">

    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    <add assembly="NLog.Appsettings.Standard" />
    </extensions>

    <!-- the targets to write to -->
    <targets>
        <!-- File Target for all log messages with basic details -->
        <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />

        <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-svc27-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

        <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
        <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />

    <target xsi:type="Database"
         name="database"
         keepConnection="true"
         useTransactions="true"
         connectionString="${appsettings:name=ConnectionStrings.DefaultConnection}"
         dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient">

      <commandText>
        INSERT INTO dbo.NLogItems (Id, EventDateTime, EventLevel, UserName, MachineName, EventMessage, ErrorSource, ErrorClass, ErrorMethod, ErrorMessage, InnerErrorMessage)
        VALUES (NEWID(), @EventDateTime, @EventLevel, @UserName, @MachineName, @EventMessage, @ErrorSource, @ErrorClass, @ErrorMethod, @ErrorMessage, @InnerErrorMessage)
      </commandText>
      <parameter name="@EventDateTime" layout="${date:s}" />
      <parameter name="@EventLevel" layout="${level}" />
      <parameter name="@UserName" layout="${aspnet-user-identity}" />
      <parameter name="@MachineName" layout="${machinename}" />
      <parameter name="@EventMessage" layout="${message}" />
      <parameter name="@ErrorSource" layout="${event-context:item=error-source}" />
      <parameter name="@ErrorClass" layout="${event-context:item=error-class}" />
      <parameter name="@ErrorMethod" layout="${event-context:item=error-method}" />
      <parameter name="@ErrorMessage" layout="${event-context:item=error-message}" />
      <parameter name="@InnerErrorMessage" layout="${event-context:item=inner-error-message}" />
    </target>
    </targets>


    <!-- rules to map from logger name to target -->
    <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />

        <!--Output hosting lifetime messages to console target for faster startup detection -->
        <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />

        <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
        <logger name="Microsoft.*" maxlevel="Info" final="true" />
        <logger name="System.Net.Http.*" maxlevel="Info" final="true" />

        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />

    <logger name="*" minlevel="Info" writeTo="database" />
    </rules>
</nlog>
Drop table if exists [NLogItems]

CREATE TABLE [dbo].[NLogItems](
    [Id] uniqueidentifier NOT NULL,
    [EventDateTime] [datetime] NOT NULL,
    [EventLevel] [nvarchar](50) NOT NULL,
    [UserName] [nvarchar](255) NOT NULL,
    [MachineName] [nvarchar](255) NOT NULL,
    [EventMessage] [nvarchar](max) NOT NULL,
    [ErrorSource] [nvarchar](255) NOT NULL,
    [ErrorClass] [nvarchar](512)  NULL,
    [ErrorMethod] [nvarchar](512)  NULL,
    [ErrorMessage] [nvarchar](max)  NULL,
    [InnerErrorMessage] [nvarchar](max)  NULL
 CONSTRAINT [PK_NLogItems] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Here is a picture of my Nugets:

在此处输入图像描述

I've also looked in SQL Profiler and it seems like the Insert statement is not even coming across the wire.

NLog 5.0 introduces several breaking changes , and one is extracting the Database-Target into its own NLog.Database nuget-package. So you need to install this nuget-package to use database-target.

It is always a good idea to look at the NLog InternalLogger output to diagnose issues with NLog. It should say something like:

ArgumentException: Target type-alias is unknown: 'Database'. Extension NLog.Database not included?

Alternative one can enable throwConfigExceptions="true" and it will throw exceptions when detecting issues with NLog config:

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

See also: https://github.com/NLog/NLog/wiki/Logging-troubleshooting

Full working example after responses from Rolf Kristensen and AlwaysLearning

<?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"
      internalLogLevel="Info"
      internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">

    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
        <add assembly="NLog.Appsettings.Standard" />
    </extensions>

    <!-- the targets to write to -->
    <targets>
        <!-- File Target for all log messages with basic details -->
        <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />

        <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-svc27-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" />

        <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
        <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />

    <target xsi:type="Database"
         name="dbPush"
         keepConnection="true"
         useTransactions="true"
          connectionString="${appsettings:name=ConnectionStrings.DefaultConnection}"
            dbProivder="Microsoft.Data.SqlClient,Microsoft.Data.SqlClient">

      <commandText>
        INSERT INTO dbo.NLogItems ([Id]
        ,[EventDateTime]
        ,[EventLevel]
        ,[UserName]
        ,[MachineName]
        ,[EventMessage]
        ,[ErrorMessage]
        ,[ErrorType]
        ,[ErrorSource]
        ,[ErrorStackTrace]
        ,[InnerErrorMessage])
        VALUES (NEWID(), @EventDateTime, @EventLevel, @UserName, @MachineName, @EventMessage, 
               @ErrorMessage, @ErrorType, @ErrorSource, @ErrorStackTrace, @InnerErrorMessage)
      </commandText>

      <parameter name="@EventDateTime" layout="${date}" dbtype="DateTime" />
      <parameter name="@EventLevel" layout="${level}" />
      <parameter name="@UserName" layout="${environment-user}" />
      <parameter name="@MachineName" layout="${machinename}" />
      <parameter name="@EventMessage" layout="${message}" />
      <parameter name="@ErrorMessage" layout="${exception:format=message}" />
      <parameter name="@ErrorType" layout="${exception:format=type}" />
      <parameter name="@ErrorSource" layout="${exception:format=source}" />
      <parameter name="@ErrorStackTrace" layout="${exception:format=stacktrace}" />
      <parameter name="@InnerErrorMessage" layout="${exception:format=type,message,method,source,stacktrace:maxInnerExceptionLevel=5:innerFormat=shortType,message,method,source,stacktrace}" />
    </target>
    </targets>


    <!-- rules to map from logger name to target -->
    <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />

        <!--Output hosting lifetime messages to console target for faster startup detection -->
        <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />

        <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
        <logger name="Microsoft.*" maxlevel="Info" final="true" />
        <logger name="System.Net.Http.*" maxlevel="Info" final="true" />

        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />

    <logger name="*" minlevel="Trace" writeTo="dbPush" />
    </rules>
</nlog>
CREATE TABLE [dbo].[NLogItems](
    [Id] [uniqueidentifier] NOT NULL,
    [EventDateTime] [datetime] NOT NULL,
    [EventLevel] [nvarchar](50) NOT NULL,
    [UserName] [nvarchar](255) NOT NULL,
    [MachineName] [nvarchar](255) NOT NULL,
    [EventMessage] [nvarchar](max) NOT NULL,
    [ErrorMessage] [nvarchar](255) NOT NULL,
    [ErrorType] [nvarchar](255) NOT NULL,
    [ErrorSource] [nvarchar](max) NULL,
    [ErrorStackTrace] [nvarchar](max) NULL,
    [InnerErrorMessage] [nvarchar](max) NULL,
 CONSTRAINT [PK_NLogItems] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.\\;Database=Blazor_DEV;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "SessionTimeoutSettings": {
    "SessionTimeout": 15
  },
}

在此处输入图像描述

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM