.netcore入门32:asp.net core集成NLog
程序员文章站
2024-01-30 22:04:58
...
环境:
- window10 x64
- asp.net core 3.1
- vs2019
- NLog.Web.AspNetCore 4.9.3
一、准备aspnetcore webapi项目
新建一个webapi项目(工程名称:NLog-Trial
)即可,略。
二、安装nuget包
<ItemGroup>
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />
</ItemGroup>
三、在Programe.cs文件中配置NLog
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
//先清空所有的日志记录提供程序
logging.ClearProviders();
//使用微软提供的控制台输出
logging.AddConsole();
//引入NLog
logging.AddNLog();
//将NLog中的日志输出级别设置最低,这样所有的日志都会转发到NLog,然后由NLog进行二次过滤
logging.AddFilter<NLogLoggerProvider>(level => level >= LogLevel.Trace);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
四、在项目目录下新建nlog.config文件
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="Trace"
internalLogFile="${basedir}/logs/internal-nlog.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="allfile" fileName="${basedir}/logs/nlog-all-${shortdate}.log"
layout="[${longdate}] [${event-properties:item=EventId_Id}] [${uppercase:${level}}] [${logger}] ${message} ${exception:format=tostring}" />
<!-- 应用程序日志 -->
<target xsi:type="File" name="ownFile-web" fileName="${basedir}/logs/nlog-own-${shortdate}.log"
layout="[${longdate}] [${event-properties:item=EventId_Id}] [${uppercase:${level}}] [${logger}] [url: ${aspnet-request-url}] [action: ${aspnet-mvc-action}] ${message} ${exception:format=tostring}" />
<!-- 用于记录所有 -->
<target xsi:type="File" name="seriousfile" fileName="${basedir}/logs/nlog-serious-${shortdate}.log"
layout="[${longdate}] [${event-properties:item=EventId_Id}] [${uppercase:${level}}] [${logger}] ${message} ${exception:format=tostring}" />
</targets>
<rules>
<!-- 将日志框架分发的所有日志消息记录到文件:allfile -->
<logger name="Microsoft.*" minlevel="Trace" writeTo="allfile" />
<logger name="System.*" minlevel="Trace" writeTo="allfile" />
<!-- 将日志框架分发的当前web程序中的日志记录到文件:ownFile-web -->
<logger name="NLog_Trial.*" minlevel="Trace" writeTo="ownFile-web" />
<!-- 将日志框架分发的Warning级别以上的日志记录到文件:seriousfile -->
<logger name="*" minlevel="Warning" writeTo="seriousfile" />
</rules>
</nlog>
五、在控制器中写入测试代码(WeatherForecastController.cs)
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
//...
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogTrace("trace");
_logger.LogDebug("debug");
_logger.LogInformation("info");
_logger.LogWarning("warn");
_logger.LogError("error");
_logger.LogCritical("critical");
using (_logger.BeginScope("测试日志的Scope"))
{
_logger.LogTrace("scope-trace");
_logger.LogDebug("scope-debug");
_logger.LogInformation("scope-info");
_logger.LogWarning("scope-warn");
_logger.LogError("scope-error");
_logger.LogCritical("scope-critical");
}
_logger.LogTrace("Scope已经结束了。。。");
var rng = new Random();
throw new Exception("测试异常日志");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
//...
}
六、运行查看效果
输出文件:
文件内容:nlog-serious-2020-11-15
上一篇: 解析yml文件 转换 Map
下一篇: 一些功能