ASP.NET Core项目中使用NLog记录操作日志
作者:互联网
ASP.NET Core支持与多种第三方日志程序集成,具体清单见下面的截图。本文介绍ASP.NET Core项目中使用NLog程序记录程序。
NLog是一个开源的、灵活的日志框架,它支持多个版本.net中集成调用,具体清单如下所示。
NLog支持将日志记录到控制台、本地文件、数据库等位置,本文记录如何在ASP.NET Core项目中添加NLog,并将日志输出到控制台、本地文件。
打开之前创建的电影数据维护程序,在VSCode终端中执行下列命令添加NLog相关引用。
dotnet add package NLog
dotnet add package NLog.Web.AspNetCore
在program.cs文件的CreateHostBuilder中启用NLog
...
using NLog.Web;
...
namespace TestMVCMySql
{
public class Program
{
...
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseNLog();
...
}
}
在控制器类中增加日志属性,并通过构造函数传入日志实例,然后在增删改查函数中开头处加入日志记录代码。
public class MovieController : Controller
{
private readonly RazorPagesMovieContext _context;
private readonly ILogger<MovieController> _logger;
public MovieController(RazorPagesMovieContext context,ILogger<MovieController> logger)
{
_context = context;
_logger=logger;
}
...
...
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(int id)
{
_logger.LogInformation(string.Format("DeleteConfirmed movie(id={0})",id));
var movie = _context.Movies.SingleOrDefault(m => m.Id == id);
_context.Movies.Remove(movie);
_context.SaveChanges();
return RedirectToAction("Index");
}
...
...
}
最后在项目根目录下新建nlog.config文件,然后复制参考文件5中的配置并进行调整(主要是修改参考文献5中的日志文件路径)。配置文件中,targets节用于定义写入位置(通过type属性设置),本文中主要是命令行和本地文件,而rules节定义写入规则。
<?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="nlog-AspNetCore.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- File Target for all log messages with basic details -->
<target xsi:type="File" name="allfile" fileName="nlog-AspNetCore-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="nlog-AspNetCore-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}| body: ${aspnet-request-posted-body}" />
<!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
<target xsi:type="Console" name="lifetimeConsole" layout="${level:truncate=4:lowercase=true}: ${logger}[0]${newline} ${message}${exception:format=tostring}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Output hosting lifetime messages to console target for faster startup detection -->
<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
<!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="System.Net.Http.*" maxlevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
最后是运行效果,运行电影数据维护程序,点击删除、编辑、查看详细信息等链接后,控制台中的输出如下所示:
本地文件中记录的日志内容如下: 将日志记录到数据库中相对而言更复杂一些,需要在nlog.config中做更多的配置,后续还会继续学习记录。
参考文献:
[1]https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-5.0
[2]https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0#third-party-logging-providers
{3]https://blog.csdn.net/qin_yu_2010/article/details/81395098
[4]https://nlog-project.org/
[5]https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-5
[6]https://zhaobingwang.blog.csdn.net/article/details/81568747?spm=1001.2101.3001.6650.6&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EOPENSEARCH%7Edefault-6.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EOPENSEARCH%7Edefault-6.no_search_link
[7]https://github.com/NLog/NLog
标签:Core,ASP,https,...,NLog,context,日志,logger 来源: https://blog.csdn.net/gc_2299/article/details/115258086