.Net Core学习教程之在Mvc中简单的使用日志组件

所属分类: 网络编程 / ASP.NET 阅读数: 1889
收藏 0 赞 0 分享

前言

本文是基于 .Net Core 2.0,只是蜻蜓点水,并非深入浅出。给大家介绍了关于.Net Core在Mvc中使用日志组件的相关内容,分享出供大家参考学习,下面话不多说了,来一起看看详细的介绍吧

目录

使用内置的日志组件

简单过渡到第三方组件 - NLog 

使用内置的日志

下面使用控制器 HomeController.cs 进行演示。

需要 using Microsoft.Extensions.Logging;

方案一:

public class HomeController : Controller
 {
  private readonly ILogger _logger ;

  public HomeController(ILoggerFactory loggerFactory)
  {
   _logger = loggerFactory.CreateLogger(typeof(HomeController));
  }
 }

方案二:

public class HomeController : Controller
 {
  private readonly ILogger _logger ;

  public HomeController(ILogger<HomeController> logger)
  {
   _logger = logger;
  }
 }

方案三:

public class HomeController : Controller
 {
  private readonly ILogger _logger ;

  public HomeController(ILogger logger)
  {
   _logger = logger;
  }
 }

三种都是通过注入的方式获取日志记录器对象,在过去,我们会自己独立封装类似这些 Debug、Info 和 Error 等不同日志等级的方法,现在我们看看内置的方法是如何使用的? 

在 HomeController 内添加 Index() 方法进行测试。

public IActionResult Index()
  {
   _logger.LogDebug($"测试:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
   _logger.LogError($"测试:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
   _logger.LogInformation($"测试:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");

   return Json(Guid.NewGuid());
  }

在输出结果中我们可以看到,不同日志的等级在控制台中会以不同的颜色进行标注。

 

每种级别的 Log 都有多个方法重载,如 LogInformation() ,示例演示的代码中使用的是比较简单一种,也就是最后一种。

//
    // 摘要:
    //   Formats and writes an informational log message.
    //
    // 参数:
    //  logger:
    //   The Microsoft.Extensions.Logging.ILogger to write to.
    //
    //  eventId:
    //   The event id associated with the log.
    //
    //  message:
    //   Format string of the log message.
    //
    //  args:
    //   An object array that contains zero or more objects to format.
    public static void LogInformation(this ILogger logger, EventId eventId, string message, params object[] args);
    //
    // 摘要:
    //   Formats and writes an informational log message.
    //
    // 参数:
    //  logger:
    //   The Microsoft.Extensions.Logging.ILogger to write to.
    //
    //  exception:
    //   The exception to log.
    //
    //  message:
    //   Format string of the log message.
    //
    //  args:
    //   An object array that contains zero or more objects to format.
    public static void LogInformation(this ILogger logger, Exception exception, string message, params object[] args);
    //
    // 摘要:
    //   Formats and writes an informational log message.
    //
    // 参数:
    //  logger:
    //   The Microsoft.Extensions.Logging.ILogger to write to.
    //
    //  message:
    //   Format string of the log message.
    //
    //  args:
    //   An object array that contains zero or more objects to format.
    public static void LogInformation(this ILogger logger, string message, params object[] args);

其它细节以及详情,或者希望使用其它日志组件可参考官方文档:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x

简单过渡到第三方组件 - NLog

Nuget 安装 NLog.Web.AspNetCore(目前 Nuget 最新为 4.4.1,但是官方的教程却是 4.5 的,小编使用 4.4.1 进行演示)。如需 4.5+ 可参考官方:https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

下面演示如何将内置的组件简单的移植到 NLog 中。

先在根目录创建配置文件 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="c:\temp\internal-nlog.txt">


 <!-- the targets to write to -->
 <targets>
  <!-- write logs to file -->
  <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
      layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

  <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
  <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
      layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
 </targets>

 <!-- rules to map from logger name to target -->
 <rules>
  <!--All logs, including from Microsoft-->
  <logger name="*" minlevel="Trace" writeTo="allfile" />

  <!--Skip non-critical Microsoft logs and so log only own logs-->
  <logger name="Microsoft.*" maxLevel="Info" final="true" /> <!-- BlackHole without writeTo -->
  <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
 </rules>
</nlog>

修改 Startup.cs 类中的 Configure() 方法,其它地方都不需要做出任何修改。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      loggerFactory.AddNLog();  //添加NLog 
      env.ConfigureNLog("nlog.config");  //读取Nlog配置文件 

      //...    
    }

启动程序,你会发现:

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

更多精彩内容其他人还在看

asp.net网站首页根据IP自动跳转指定页面的示例

本文介绍的程序主要实现根据IP地址或地址段或IP所在城市进行自动跳转到指定页面的功能,需要的朋友可以参考下
收藏 0 赞 0 分享

asp.net无法获取iis目录的问题解决方法

本文介绍了Asp.Net无法获取IIS拾取目录的解决办法,需要的朋友可以参考下
收藏 0 赞 0 分享

.net中 发送邮件内容嵌入图片的具体实例

这篇文章主要介绍了.net中 发送邮件内容嵌入图片的具体实例,需要的朋友可以参考下
收藏 0 赞 0 分享

在.net中用CheckBoxList实现单选

用CheckBoxList实现单选的原因是我觉得CheckBoxList控件页面展示效果要好看一些,需要的朋友可以参考下
收藏 0 赞 0 分享

ASP.NET―001:GridView绑定List、页面返回值具体实现

这篇文章主要介绍了ASP.NET―GridView绑定List、页面返回值具体实现,需要的朋友可以参考下
收藏 0 赞 0 分享

Ajax实现异步刷新验证用户名是否已存在的具体方法

由于要做一个注册页面,看到许多网站上都是使用Ajax异步刷新验证用户名是否可用的,所以自己也动手做一个小实例
收藏 0 赞 0 分享

ASP.NET汉字转拼音 - 输入汉字获取其拼音的具体实现

这篇文章主要介绍了ASP.NET汉字转拼音 - 输入汉字获取其拼音的具体实现,需要的朋友可以参考下
收藏 0 赞 0 分享

.Net消息队列的使用方法

这篇文章主要介绍了.Net消息队列的使用方法,需要的朋友可以参考下
收藏 0 赞 0 分享

C# web api返回类型设置为json的两种方法

web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面为大家介绍几种不错的方法
收藏 0 赞 0 分享

asp.net获取网站目录物理路径示例

这篇文章主要介绍了asp.net获取网站目录物理路径的方法,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多