需求:NLog写日志到数据库
一、必须要安装:
System.Data.SqlClient
二、 NLog配置:
<?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"
throwConfigExceptions="true"
internalLogLevel="off"
internalLogFile="nlog.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target name="ApiTrace" xsi:type="Database" useTransactions="true"
dbProvider="System.Data.Sqlclient.SqlConnection,System.Data.Sqlclient"
connectionString="Server=127.0.0.1;Database=LogDb;UID=sa;Password=a1!"
commandText="INSERT INTO Sys_Logs (ID, Logger, Level, Host, Url , Method, Cookie, UserAgent, QueryString, Body , Message, CreateTime, IPAddress, Elapsed,UserId,UserName,ProjectName) VALUES (newId(), @Logger, @Level, @Host, @Url , @Method, @Cookie, @UserAgent, @QueryString, @Body , @Message, @CreateTime, @IPAddress, @Elapsed,@UserId,@UserName,'学生端');">
<parameter name="@Logger" layout="${logger}" />
<parameter name="@Level" layout="${uppercase:${level}}" />
<parameter name="@Host" layout="${aspnet-request-host}" />
<parameter name="@Url" layout="${aspnet-request-url:IncludeScheme=false:IncludeHost=false}" />
<parameter name="@Method" layout="${aspnet-request-method}" />
<parameter name="@Cookie" layout="${aspnet-request-headers:HeaderNames=SYSTOKEN:ValuesOnly=true}" />
<parameter name="@UserAgent" layout="${aspnet-request-useragent}" />
<parameter name="@QueryString" layout="${aspnet-request-querystring:OutputFormat=JSON}" />
<parameter name="@Body" layout="${event-properties:item=RequestBody}" />
<parameter name="@Message" layout="${message}" />
<parameter name="@CreateTime" layout="${longdate}" />
<parameter name="@IPAddress" layout="${aspnet-request-ip}" />
<parameter name="@Elapsed" layout="${event-properties:item=Elapsed}"/>
<parameter name="@UserId" layout="${event-properties:item=UserId}"/>
<parameter name="@UserName" layout="${event-properties:item=UserName}"/>
</target>
<target name="Info" xsi:type="File" layout="**************************************************************************************************************************${newline} 日志时间 : ${longdate} ${newline} 日志来源 : ${logger} ${newline} 日志级别 : ${uppercase:${level}} ${newline} 日志内容 : ${message}${newline}" fileName="${basedir}/Logs/${date:format=yyyyMM}/Info-${shortdate}.log" />
<target name="Warn" xsi:type="File" layout="**************************************************************************************************************************${newline} 日志时间 : ${longdate} ${newline} 日志来源 : ${logger} ${newline} 日志级别 : ${uppercase:${level}} ${newline} 日志内容 : ${message}${newline}" fileName="${basedir}/Logs/${date:format=yyyyMM}/Warn-${shortdate}.log" />
<target name="error" xsi:type="File" layout="**************************************************************************************************************************${newline} 日志时间 : ${longdate} ${newline} 日志来源 : ${logger} ${newline} 日志级别 : ${uppercase:${level}} ${newline} 日志内容 : ${message}${newline}" fileName="${basedir}/Logs/${date:format=yyyyMM}/ERROR-${shortdate}.log" />
<target name="debug" xsi:type="File" layout="**************************************************************************************************************************${newline} 日志时间 : ${longdate} ${newline} 日志来源 : ${logger} ${newline} 日志级别 : ${uppercase:${level}} ${newline} 日志内容 : ${message}${newline}" fileName="${basedir}/Logs/${date:format=yyyyMM}/DEBUG-${shortdate}.log" />
</targets>
<rules>
<!-- add your logging rules here -->
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="*" level="Trace" writeTo="ApiTrace" />
<logger name="*" level="Info" writeTo="Info" />
<logger name="*" level="Warn" writeTo="Warn" />
<logger name="*" level="Debug" writeTo="debug" />
<logger name="*" level="Error" writeTo="error" />
</rules>
</nlog>
三、数据库:
USE [LogDb]
GO
/****** Object: Table [dbo].[Sys_Logs] Script Date: 2023/7/14 11:17:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sys_Logs](
[ID] [nvarchar](36) NOT NULL,
[Logger] [nvarchar](50) NULL,
[Level] [nvarchar](50) NULL,
[user] [nvarchar](50) NULL,
[Url] [nvarchar](255) NULL,
[Host] [nvarchar](100) NULL,
[Method] [nvarchar](10) NULL,
[UserAgent] [nvarchar](255) NULL,
[Cookie] [nvarchar](100) NULL,
[QueryString] [nvarchar](max) NULL,
[Body] [nvarchar](max) NULL,
[Message] [nvarchar](max) NULL,
[Elapsed] [int] NULL,
[CreateTime] [datetime2](6) NULL,
[IPAddress] [nvarchar](50) NULL,
[UserId] [nvarchar](100) NULL,
[UserName] [nvarchar](500) NULL,
[ProjectName] [nvarchar](100) NULL,
CONSTRAINT [PK__Sys_Logs__3214EC278989976B] 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
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'ID'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志类型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Logger'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志等级' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Level'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志来源' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Url'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'主机地址' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Host'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'请求方式' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Method'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'浏览器标识' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'UserAgent'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Cookie' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Cookie'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'URL参数' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'QueryString'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'请求内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Body'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志信息' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Message'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'请求耗时' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'Elapsed'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'创建时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'CreateTime'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'用户来源' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'IPAddress'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作人Id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'UserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'操作人账号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'UserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'项目名称' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs', @level2type=N'COLUMN',@level2name=N'ProjectName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'日志管理' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Sys_Logs'
GO
四、Program
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
logger.Error(exception, exception.Message + " || " + exception.StackTrace + "Stopped program because of exception");
throw;
}
finally
{
LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseUrls(AppSettings.Configuration["Startup:ApiUrls"].Split(';'))
.ConfigureKestrel(serverOptions =>
{
serverOptions.AllowSynchronousIO = true;//ͬ IO
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
logging.AddDebug();
logging.AddConsole();
});
}).UseNLog();
}