ASP.NET Core支持与多种第三方日志程序集成,具体清单见下面的截图。本文介绍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.Log@R_242_4045@ion(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>
最后是运行效果,运行电影数据维护程序,点击删除、编辑、查看详细信息等链接后,控制台中的输出如下所示:
参考文献:
[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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。