//using NLog.Web; .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }).UseNLog(); // NLog: 依赖注入Nlog
完成后如下图所示:
启动项目同步连接字符串
修改网站启动Program.cs中的逻辑:
//using NLogUsage.CommonUtils; //using Microsoft.Extensions.DependencyInjection; public static void Main(string[] args) { //CreateHostBuilder(args).Build().Run(); var host = CreateHostBuilder(args).Build(); try { using (IServiceScope scope = host.Services.CreateScope()) { IConfiguration configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>(); //获取到appsettings.json中的连接字符串 string sqlString = configuration.GetSection("ConectionStrings:MySqlConnection").Value; //确保NLog.config中连接字符串与appsettings.json中同步 NLogUtil.EnsureNlogConfig("NLog.config", sqlString); } //throw new Exception("测试异常");//for test //其他项目启动时需要做的事情 //code NLogUtil.WriteDBLog(NLog.LogLevel.Trace, LogType.Web, "网站启动成功"); host.Run(); } catch (Exception ex) { //使用nlog写到本地日志文件(万一数据库没创建/连接成功) string errorMessage = "网站启动初始化数据异常"; NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Web, errorMessage, new Exception(errorMessage, ex)); NLogUtil.WriteDBLog(NLog.LogLevel.Error, LogType.Web, errorMessage, new Exception(errorMessage, ex)); throw; } }
修改完成后,如下图所示:
启动验证
启动项目,可以正常记录日志到数据库和文件: