C#6.0 Windows服务部署后Serilog日志路径异常问题
解决Windows服务中Serilog日志生成路径错误问题
问题根因
Windows服务默认工作目录为C:\Windows\System32,你当前Serilog配置使用的是相对路径(如logs/Debug/.log),导致日志文件被创建在System32目录下,而非程序部署目录。
解决方案
方案1:启动服务时切换工作目录
在服务的OnStart方法中,将当前工作目录切换到程序所在路径,这样配置中的相对路径会自动基于程序目录解析:
protected override void OnStart(string[] args) { // 获取程序执行文件所在目录 string exeDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); // 设置当前工作目录 Directory.SetCurrentDirectory(exeDir); // 初始化配置与Serilog var configuration = new ConfigurationBuilder() .SetBasePath(exeDir) .AddJsonFile("appsettings.json") .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); // 其他服务启动逻辑 }
方案2:代码中配置绝对日志路径
放弃配置文件中的相对路径,在代码里动态拼接程序目录与日志路径,直接配置Serilog的File Sink:
var logRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs"); Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Error) // 保留原有等级覆盖规则 .WriteTo.Console(outputTemplate: "【时间】{Timestamp:yyyy-MM-dd HH:mm:ss,fff}{NewLine}【等级】{Level}{NewLine}【消息】[{SourceContext}]{Message:lj}{NewLine}{Exception}{NewLine}") // Debug等级日志配置 .WriteTo.Logger(lc => lc .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Debug) .WriteTo.File(Path.Combine(logRoot, "Debug/.log"), rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(7), outputTemplate: "【时间】{Timestamp:yyyy-MM-dd HH:mm:ss,fff}{NewLine}【等级】[{Level}]{NewLine}【消息】[{SourceContext}] {Message:lj}{NewLine}{Exception}{NewLine}")) // Information等级日志配置 .WriteTo.Logger(lc => lc .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Information) .WriteTo.File(Path.Combine(logRoot, "Information/.log"), rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(7), outputTemplate: "【时间】{Timestamp:yyyy-MM-dd HH:mm:ss,fff}{NewLine}【等级】[{Level}]{NewLine}【消息】[{SourceContext}] {Message:lj}{NewLine}{Exception}{NewLine}")) // Warning、Error等级日志按相同逻辑配置 .CreateLogger();
注意事项
确保Windows服务账号拥有程序部署目录的读写权限,否则日志文件无法正常生成。
内容的提问来源于stack exchange,提问作者landon
相关产品推荐
相关产品推荐

