Files
2026-04-04 17:25:15 +08:00

57 lines
2.2 KiB
C#

using ModbusTcpToRtu;
using Serilog;
// 配置主机服务,作为 Windows 服务运行
IHost host = Host.CreateDefaultBuilder(args).UseWindowsService()
// 配置应用程序配置
.ConfigureAppConfiguration((hostingContext, config) =>
{
// 构建配置
var configuration = config
// 设置配置文件的基础路径
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
// 添加 appsettings.json 配置文件
.AddJsonFile("appsettings.json")
// 根据环境变量添加对应的配置文件(开发/生产等)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true)
// 添加环境变量配置
.AddEnvironmentVariables()
.Build();
// 设置当前工作目录
Directory.SetCurrentDirectory(hostingContext.HostingEnvironment.ContentRootPath);
// 配置 Serilog 日志
Log.Logger = new LoggerConfiguration()
// 从配置读取日志设置
.ReadFrom.Configuration(configuration)
// 从日志上下文丰富日志信息
.Enrich.FromLogContext()
// 输出到控制台
.WriteTo.Console()
// 输出到文件(错误级别,按天滚动)
.WriteTo.File("Log\\log..txt", Serilog.Events.LogEventLevel.Error, shared: true, rollingInterval: RollingInterval.Day)
.CreateLogger();
// 创建日志工厂并添加 Serilog
var loggerFactory = new LoggerFactory().AddSerilog(Log.Logger);
// 设置 Quartz 日志提供者
Quartz.Logging.LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
// 设置 Modbus.Net 日志提供者
Modbus.Net.LogProvider.SetLogProvider(loggerFactory);
})
// 配置服务
.ConfigureServices(services =>
{
// 添加后台服务 Worker
services.AddHostedService<Worker>();
// 添加日志服务
services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(Log.Logger, true));
})
.Build();
// 运行主机
await host.RunAsync();