石林彝族网站建设,建网站得钱吗,开发者选项怎么设置最流畅,网站后台管理员做链接在本系例文章的第八篇中#xff0c;我们聊过官方的日志实现#xff0c;即《.NET6之MiniAPI(八)#xff1a;日志》。但官方的日志功能更多是提供了一个实现基础#xff0c;对于要求一个灵活#xff0c;强大#xff0c;方便的日志体系#xff0c;官方的还是有差距的#… 在本系例文章的第八篇中我们聊过官方的日志实现即《.NET6之MiniAPI(八)日志》。但官方的日志功能更多是提供了一个实现基础对于要求一个灵活强大方便的日志体系官方的还是有差距的那么本篇就介绍一下NLog这款强大灵活方便的日志库在MiniAPI中的使用。直入主题首先引入NeGut包NLog.Web.AspNetCore添加代码实现很简单using NLog;
using NLog.Web;//启动日志
var logger NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug(init main);
try
{var builder WebApplication.CreateBuilder(args);//配置日志builder.Logging.ClearProviders();builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);builder.Host.UseNLog();var app builder.Build();//使用日志app.MapGet(/logtest, () {app.Logger.LogTrace(LogTrace);app.Logger.LogDebug(LogDebug);app.Logger.LogWarning(LogWarning);app.Logger.LogInformation(LogInformation);app.Logger.LogError(LogError);app.Logger.LogCritical(new Exception(eLogCritical), LogCritical);return logtest;});app.MapGet(/myvalue, MyService.GetMyValue);app.Run();
}
catch (Exception exception)
{//异常时处理日志logger.Fatal(exception, Stopped program because of exception);
}
finally
{NLog.LogManager.Shutdown();
}class MyService
{public static string GetMyValue(ILoggerMyService logger){logger.LogInformation(TestService.GetMyValue);return MyValue;}
}NLog的真正方便在配置的丰富通过配置灵活地实现不日志方式不同信息项目的采集。NLog的配置以nlog.config文件名保存在项目根目录下当然也可以通过修改启动日志的LoadConfigurationFramAppSettings来配置nlog.config路径。配置主要通过targets节点和rules节点协助实现配置targets主要是配置保存或显示日志的方式是txt文件还json文件以及layout中日志的内容具体target的属性有很多参见https://github.com/NLog/NLog/wiki/File-target。另外一个就是layout中也就是将来的日志信息有那些元素可参见https://nlog-project.org/config/?tablayout-renderers。rules主要是配置不同的功能模块日志级别等信息参见https://github.com/nlog/nlog/wiki/Configuration-file#rules。下面的案例配置实现了官方模板自带的allfile和ownFile-web两个txt格式的模板和一个jsonfile的模板同时还有一个彩色控制台模板各个模板的属性官方文档比较详细这里就不展开了?xml version1.0 encodingutf-8 ?
nlog xmlnshttp://www.nlog-project.org/schemas/NLog.xsdxmlns:xsihttp://www.w3.org/2001/XMLSchema-instanceautoReloadtrueinternalLogLevelInfo!-- enable asp.net core layout renderers --extensionsadd assemblyNLog.Web.AspNetCore//extensions!-- the targets to write to --targets!-- File Target for all log messages with basic details --target xsi:typeFile nameallfile fileName${basedir}\logs\nlog-AspNetCore-all-${shortdate}.loglayout${longdate}|${event-properties:itemEventId_Id:whenEmpty0}|${level:uppercasetrue}|${logger}|${message} ${exception:formattostring} /!-- File Target for own log messages with extra web details using some ASP.NET core renderers --target xsi:typeFile nameownFile-web fileName${basedir}\logs\nlog-AspNetCore-own-${shortdate}.loglayout${longdate}|${event-properties:itemEventId_Id:whenEmpty0}|${level:uppercasetrue}|${logger}|${message} ${exception:formattostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite} /!--json格式--target namejsonfile xsi:typeFile fileName${basedir}\logs\${shortdate}.jsonlayout xsi:typeJsonLayout includeAllPropertiestrueattribute nametime layout${date:formatO} /attribute namemessage layout${message} /attribute namelogger layout${logger}/attribute namelevel layout${level}/attribute nameexception layout${exception} /attribute namerequest encodefalse layout typeJsonLayoutattribute nameaspnet-request-ip layout${aspnet-request-ip}/attribute nameaspnet-Request-Url layout${aspnet-Request-Url}/attribute nameaspnet-Request-Host layout${aspnet-Request-Host}/attribute nameaspnet-Request-Method layout${aspnet-Request-Method}//layout/attribute/layout/target!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection --target xsi:typeColoredConsole namelifetimeConsole layout${MicrosoftConsoleLayout} highlight-row conditionlevel LogLevel.Error backgroundColorNoChange foregroundColorNoChange/highlight-row conditionlevel LogLevel.Fatal backgroundColorNoChange foregroundColorNoChange/highlight-row conditionlevel LogLevel.Warn backgroundColorNoChange foregroundColorNoChange/highlight-word textinfo conditionlevel LogLevel.Info backgroundColorNoChange foregroundColorGreen ignoreCasetrue regexinfo wholeWordstrue compileRegextrue/highlight-word textwarn conditionlevel LogLevel.Warn backgroundColorNoChange foregroundColorYellow ignoreCasetrue regexwarn wholeWordstrue compileRegextrue/highlight-word textfail conditionlevel LogLevel.Error backgroundColorNoChange foregroundColorRed ignoreCasetrue regexfail wholeWordstrue compileRegextrue/highlight-word textcrit conditionlevel LogLevel.Fatal backgroundColorNoChange foregroundColorDarkRed ignoreCasetrue regexcrit wholeWordstrue compileRegextrue//target/targets!-- rules to map from logger name to target --rules!--All logs, including from Microsoft--logger name* minlevelTrace writeToallfile /!--Output hosting lifetime messages to console target for faster startup detection --logger name* minlevelTrace writeTolifetimeConsole /!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) --logger nameMicrosoft.* maxlevelInfo finaltrue /logger nameSystem.Net.Http.* maxlevelInfo finaltrue /!--json格式--logger name* minlevelTrace writeTojsonfile /logger name* minlevelTrace writeToownFile-web //rules
/nlog这里的appsettings.jsons配置如下{Logging: {LogLevel: {Default: Trace,Microsoft.AspNetCore: Trace}},AllowedHosts: *
}根据配置看看具体的实现效果控制台结果2022-02-20.json结果nlog-AspNetCore-own-2022-02-20.log结果nlog-AspNetCore-all-2022-02-20.log结果