同步更新於個人部落格
NLog進階範例
選擇ASP.NET Core Web API專案範本,並執行下一步
命名你的專案名稱,並選擇專案要存放的位置。
直接進行下一步
using NLog;
using NLog.Web;
//初始化NLog
var logger = LogManager.Setup()
//載入Configuration並且讀取appsetting來使用
.LoadConfigurationFromAppSettings()
.GetCurrentClassLogger();
try {
logger.Debug("init main");
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Logging.ClearProviders();
builder.Host.UseNLog();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//以下省略
設定NLog,包含
ILogger | NLog | |
---|---|---|
Level 0 | Trace | Trace |
Level 1 | Debug | Debug |
Level 2 | Information | Info |
Level 3 | Warning | Warn |
Level 4 | Error | Error |
Level 5 | Critical | Fatal |
Level 6 | None | NLog沒有 |
{
"NLog": {
"throwConfigExceptions": true,
"targets": {
"async": true,
"logfile": {
"type": "File",
"fileName": "c:/temp/nlog-${shortdate}.txt"
},
"logconsole": {
"type": "Console"
}
},
"rules": [
{
"logger": "Microsoft.AspNetCore",
"minLevel": "Warn",
"writeTo": "logconsole"
},
{
"logger": "*",
"minLevel": "Info",
"writeTo": "logfile"
}
]
}
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get() {
//新增一個類型
var StudentObject = new Student() { Id = 4, Name = "Bill", Age = 20 };
//新增一個匿名類型
var position = new { Latitude = 25, Longitude = 134 };
//寫log等級為error的log,當需要紀錄物件時需要透過{@該物件}來表示
_logger.LogError("Error Value: {@StudentObject}", StudentObject);
_logger.LogError("Error Value: {@position}", position);
return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
F5執行後,依照下列步驟操作,並確認結果
執行後查看log檔案,這次寫到C:\temp底下
最後其實會發現Serilog相對來說比較容易使用,也建議使用serilog
黑暗執行緒
中文輸出為unicode問題
target參數中文解說
非同步使用方式與縮寫