_logger.LogInformation("你訪問了首頁"); _logger.LogWarning("警告信息"); _logger.LogError("錯誤信息");
使用DI 直接可以使用對象。
日志級別:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical
級別包含范圍由大到小 ,如 Trace 就包含了所有信息。
NLog 使用
NLog 在 ASP.NET Core中的使用。
1.添加引用。
Install-Package NLog.Extensions.Logging -Pre
2.添加nlog.config 文件在項目里。
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Warn" internalLogFile="internal-nlog.txt"> <!-- define various log targets --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
3.在 Startup.cs -》 Configure
Host.CreateDefaultBuilder(args)
.ConfigureLogging((ILoggingBuilder logBuilder) =>
{
logBuilder.AddNLog();
logBuilder.AddConsole();
NLog.LogManager.LoadConfiguration("nlog.config");
})
運行程序,你就會發現,項目下多了兩個文件,證明成功執行。
這里 nlog-all-*.log 是記錄所有日志,nlog-own-*.log 記錄跳過Microsoft 開頭的類庫輸出的相關信息,剩下的信息。
4.發布(dotnet publish)注意事項
在 project.json 的 publishOptions節點 加入 nlog.config
"publishOptions": { "include": [ "wwwroot", "Views", "appsettings.json", "web.config", "nlog.config"//加上nlog配置文件 ] },