.NET 5 Web API部署本地IIS后日志无法写入文件的问题
问题
将.NET 5 Web API部署到本地IIS后,自定义Logger无法写入日志文件。本地调试时日志能正常生成在TestWebAPI\TestWebAPI\bin\Debug\net5.0\Logs\LogFile.txt,但部署后调用ThrowError端点时,虽然能正常返回错误响应,却没有日志生成。手动在发布目录创建Logs/LogFile.txt也无效。
部署步骤:
- 创建“无托管代码”CLR选项的应用程序池
- 新建站点并分配该应用池
- 发布项目到目录并设置站点物理路径
- 浏览器访问站点(其他端点正常)
Logger.cs 代码
using System; using System.IO; public static class Logger { private static readonly object lockObject = new object(); private static string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs", "LogFile.txt"); static Logger() { EnsureLogFileExists(); } private static void EnsureLogFileExists() { //for thread safety lock (lockObject) { try { string directoryPath = Path.GetDirectoryName(logFilePath); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } if (!File.Exists(logFilePath)) { File.Create(logFilePath).Close(); } } catch (Exception ex) { Console.WriteLine($"Error creating log file: {ex.Message}"); } } } public static void Log(string message, Exception ex = null) { EnsureLogFileExists(); // For thread safety lock (lockObject) { try { using (StreamWriter writer = new StreamWriter(logFilePath, true)) { string logEntry = $"Time: {DateTime.Now:yyyy-MM-dd HH:mm:ss}"; writer.WriteLine($"Error Message - {message}"); if (ex != null) { logEntry += $"\nException Details:\n{ex.ToString()}"; } writer.WriteLine(logEntry); writer.Write(" "); writer.WriteLine("---End of exception-------------------------------------------------------------------------------------------------------------------------"); } } catch (Exception logException) { Console.WriteLine($"Error writing to log file: {logException.Message}"); } } } }
调用日志的控制器方法
[HttpGet(template: nameof(ThrowError))] public IActionResult ThrowError() { try { //will throw an out of range error int[] numbers = { 1, 2, 3 }; int value = numbers[10]; } catch (Exception ex) { //log the error to the text file Logger.Log(ex.Message.ToString(), ex); } return BadRequest("An error occurred. Check the log for details."); }
排查与解决方法
1. 修复应用程序池CLR设置
.NET 5在IIS上依赖ASP.NET Core Module运行,不能使用“无托管代码”设置:
- 打开IIS管理器 → 应用程序池 → 选中目标池 → 高级设置
- 托管管道模式改为集成,CLR版本改为v4.0,保存设置后重启应用池
2. 配置目录读写权限
IIS应用程序池默认身份(ApplicationPoolIdentity)没有发布目录的读写权限:
- 右键站点物理路径文件夹 → 属性 → 安全 → 编辑 → 添加
- 输入
IIS AppPool\[你的应用程序池名称](例如IIS AppPool\TestWebAPIPool),勾选写入和修改权限,应用保存
3. 验证日志路径正确性
AppDomain.CurrentDomain.BaseDirectory在IIS环境下可能解析异常,可临时修改控制器方法输出路径验证:
[HttpGet(template: nameof(ThrowError))] public IActionResult ThrowError() { try { int[] numbers = { 1, 2, 3 }; int value = numbers[10]; } catch (Exception ex) { Logger.Log(ex.Message.ToString(), ex); } // 临时返回日志路径用于验证 return BadRequest($"Log path: {Logger.logFilePath}"); }
若路径错误,改用IWebHostEnvironment获取项目根路径:
- 在控制器注入
IWebHostEnvironment:private readonly IWebHostEnvironment _env; public YourController(IWebHostEnvironment env) { _env = env; } - 修改Logger的路径逻辑,通过注入的
_env.ContentRootPath拼接日志路径
4. 捕获具体错误信息
当前代码用Console.WriteLine输出的错误在IIS中无法查看,改为写入Windows事件查看器:
修改Logger中catch块代码:
catch (Exception ex) { System.Diagnostics.EventLog.WriteEntry("TestWebAPI", $"Log error: {ex.ToString()}", System.Diagnostics.EventLogEntryType.Error); }
打开事件查看器 → Windows日志 → 应用程序,查看来源为TestWebAPI的错误条目,获取具体失败原因
5. 检查权限继承设置
若发布目录权限未继承父目录设置:
- 右键文件夹 → 属性 → 安全 → 高级 → 勾选“包括可从该对象的父项继承的权限”,应用保存
内容的提问来源于stack exchange,提问作者BOO1
相关产品推荐
相关产品推荐

