nlog-config.xml 配置文件:
<?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="false"
internalLogLevel="info"
internalLogFile="Logs/SysNlog.log">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target name="db"
xsi:type="Database"
connectionString="${var:NLOG_CONNECTION_STRING}"
commandType="StoredProcedure"
commandText="[dbo].[SP_InsertLog]">
<parameter name="@traceId" layout="${aspnet-TraceIdentifier}" />
<parameter name="@eventId" layout="${event-properties:EventId}" />
<parameter name="@user" layout="${aspnet-user-identity}" />
<parameter name="@application" layout="APP_WEB" />
<parameter name="@level" layout="${level}" />
<parameter name="@category" layout="${logger}" />
<parameter name="@message" layout="${message}" />
<parameter name="@properties" layout="${all-event-properties:separator=|}" />
<parameter name="@exception" layout="${exception:tostring}" />
<parameter name="@clientIP" layout="${aspnet-request-ip}" />
<parameter name="@addTime" layout="${date:universalTime=True}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="db" />
</rules>
</nlog>
appsettings.json配置
{
"ConnectionStrings": {
"testDatabase": "Data Source=(local); Initial Catalog=TestDB; User Id=sa; Password=Sa; MultipleActiveResultSets=True;",
"LogDatabase": "Data Source=(local); Initial Catalog=TestDB_Log; User Id=sa; Password=Sa; MultipleActiveResultSets=True;"
},
"Encoding": "GBK",
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Microsoft.AspNetCore.Mvc": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"Default": "Information"
}
}
}
STARTUP.CS
// NLog 数据库配置
NLog.LogManager.Configuration.FindTargetByName<DatabaseTarget>("db").ConnectionString = Configuration.GetConnectionString("LogDatabase");
存储:
create procedure [dbo].[SP_InsertLog](
@traceId nvarchar(32),
@eventId int,
@user nvarchar(450),
@application nvarchar(450),
@level nvarchar(8),
@category nvarchar(450),
@message nvarchar(max),
@properties nvarchar(max),
@exception nvarchar(max),
@clientIP nvarchar(450),
@addTime datetime
)
as
begin
insert into dbo.[LogTable]([TraceId],[EventId], [User], [Application], [Level], [Category], [Message], [Properties], [Exception], [ClientIP], [AddTime])
values(@traceId, @eventId, @user, @application, @level, @category, @message, @properties, @exception, @clientIP, @addTime);
end
Program.cs
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog("Log/nlog-config.xml").GetCurrentClassLogger();
try
{
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "异常信息");
throw;
}
finally { NLog.LogManager.Shutdown(); }
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseNLog();
}