NETCORE - 日誌外掛 Microsoft.Extensions.Logging
netcore的預設日誌外掛為 Microsoft.Extensions.Logging,已整合在框架中。
使用樣例:
namespace RailGraph.Controllers { [ApiController] [Route("[controller]")] public class ANeo4jController : ControllerBase { public ILogger<ANeo4jController> logger; public ANeo4jController(ILogger<ANeo4jController> _logger) { this.logger = _logger; } [HttpGet] [Route("GetModelDataAsync")] public async Task<ActionResult> GetModelDataAsync(int fileId) { try { logger.LogInformation($"介面進入呼叫:GetModelDataAsync,引數:{fileId}"); logger.LogInformation($"介面呼叫完成,成功返回。"); return Ok(""); } catch (Exception ex) { return BadRequest(ex.Message + ex.InnerException?.Message); } } } }
如需要把日誌寫到檔案中。
則需要增加外掛:
Karambolo.Extensions.Logging.File
在專案的Program.cs中配置
#region == 預設的 Microsoft.Extensions.Logging 日誌 == var logRootPath = AppContext.BaseDirectory; var logFiles = new[] { new LogFileOptions { Path = $"logs/log-{DateTime.Now.ToString("yyyyMMdd")}.txt" } }; builder.Logging.AddConsole(); builder.Logging.AddFile(options => { //options.DateFormat = "yyyyMMdd"; //配置檔案根目錄 options.RootPath = logRootPath; //配置檔名稱 options.Files = logFiles; }); #endregion
end.