一、内置日志的使用
上一篇:如何在后台运行一个任务 中使用到了内置的日志,直接在构造中注入一下,然后直接使用即可, 非常方便
1. public TokenRefreshService(ILogger<TokenRefreshService> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("Service starting"); //************ }
然后在【输出】窗口中就可以看到输出的日志了:
想把它输出到txt中, 没找到相应的方法,试试常见的Nlog吧
二、使用Nlog将日志输出到文件
A.安装Nlog
在NuGet中搜索并安装 NLog.Web.AspNetCore , 当前版本是4.5.4
B.添加配置文件
新建一个文件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" throwConfigExceptions="true" internalLogLevel="info" internalLogFile="d:\log\internal-nlog.txt"> <!-- the targets to write to --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="d:\log\nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- another file log, only own logs. Uses some ASP.NET core renderers --> <target xsi:type="File" name="ownFile-web" fileName="d:\log\nlog-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /> </targets> <!-- rules to map from logger name to target --> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip non-critical Microsoft logs and so log only own logs--> <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole --> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
C.修改Program.cs文件
在 .UseStartup<Startup>() 后添加一句 .UseNLog()