十年河东,十年河西,莫欺少年穷
学无止境,精益求精
Net6引入Nlog请参考:https://www.cnblogs.com/chenwolong/p/nlog.html
项目引入:
<PackageReference Include="NLog" Version="5.0.0" /> <PackageReference Include="NLog.Extensions.Logging" Version="5.0.0" /> <PackageReference Include="NLog.Web.AspNetCore" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.31" />
增加 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="Info" internalLogFile="logs/internal-nlog-AspNetCore.txt"> <!-- enable asp.net core layout renderers --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions> <!-- the targets to write to --> <targets> <target xsi:type="File" name="ownFile-web" fileName="logs/logweb-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" archiveAboveSize="100000" maxArchiveFiles="30" /> </targets> <!-- rules to map from logger name to target --> <rules> <logger name="*" minlevel="Error" writeTo="ownFile-web" /> </rules> </nlog>
注入Nlog
services.AddLogging(log => { log.AddConsole(); log.AddNLog(); log.SetMinimumLevel(LogLevel.Error); });
测试Nlog
private readonly ILogger<LoginController> logger; private readonly ITokenService _Service; /// <summary> /// 构造函数注入 /// </summary> /// <param name="service"></param> public LoginController(ITokenService service, ILogger<LoginController> logger) { _Service = service; this.logger = logger; } /// <summary> /// SSO 对接接口 /// </summary> /// <returns></returns> [HttpPost] [Route("JwtLogin")] public IActionResult JwtLogin([FromBody] LoginModel data) { logger.LogError("这只是个测试,不用紧张"); var result = _Service.IsAuthenticated(data); return Ok(result); }
日志如下:
@天才卧龙的博客