在使用SqlSugarCore时,我们可以通过集成第三方日志组件NLog来记录数据库操作日志。以下是如何集成NLog的示例代码:
- 首先,需要安装NLog和NLog.Web.AspNetCore两个NuGet包。
Install-Package NLog
Install-Package NLog.Web.AspNetCore
- 在项目根目录中创建NLog配置文件
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"
throwConfigExceptions="true"
internalLogLevel="info"
internalLogFile="internal-nlog.txt">
<!-- 配置日志的输出目标 -->
<targets>
<!-- 输出到文件 -->
<target xsi:type="File" name="logfile" fileName="logs/${shortdate}.log" layout="${longdate}|${level:uppercase=true}|${message}" />
</targets>
<!-- 配置日志的路由规则 -->
<rules>
<!-- 所有日志都输出到文件 -->
<logger name="*" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
- 在Startup.cs中配置NLog:
using Microsoft.Extensions.Logging;
using NLog.Web;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// 添加NLog日志服务
services.AddSingleton<ILoggerFactory, LoggerFactory>()
.AddNLog(); // 添加NLog日志配置
// 其他服务配置...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 其他配置...
}
}
- 在SqlSugar配置中使用NLog记录日志:
public class SqlSugarConfig
{
public static void ConfigureSqlSugar(IServiceCollection services)
{
// 配置SqlSugar
services.AddSqlSugar(new List<ConnectionConfig>
{
new ConnectionConfig
{
ConnectionString = "your_connection_string",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true
},
AopEvents = new AopEvents
{
OnLogExecuting = (sql, pars) =>
{
NLog.LogManager.GetCurrentClassLogger().Info($