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; } }
public static void Main(string[] args) { var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); var host = CreateHostBuilder(args).Build();//.Run(); try { using (IServiceScope scope = host.Services.CreateScope()) { IConfiguration configuration = scope.ServiceProvider.GetRequiredService <IConfiguration>(); string sqlString = configuration.GetSection("ConnectionStrings:MySqlConnection").Value; NLogUtil.EnsureNlogConfig("Nlog.config", sqlString); } logger.Info("网站启动成功"); host.Run(); } catch (Exception ex) { 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; } finally { //确保在应用程序退出之前停止内部计时器/线程(避免在Linux上出现分段错误) NLog.LogManager.Shutdown(); } }