在 Mvc 中简单使用日志组件

  基于 .Net Core 2.0,本文只是蜻蜓点水,并非深入浅出。

目录

  • 使用内置的日志组件
  • 简单过渡到第三方组件 - 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配置文件 //...
}

  启动程序,你会发现:

【原文】http://www.cnblogs.com/liqingwen/p/8613538.html


相关的文章:

  《[.Net Core] 简单读取 json 配置文件

  《[.Net Core] 简单使用 Mvc 内置的 Ioc

  《[.Net Core] 简单使用 Mvc 内置的 Ioc(续)

  《[.Net Core] 在 Mvc 中简单使用日志组件

最新文章

  1. Wireshark
  2. noip200802排座椅
  3. 使用自己的ClassLoader实现热替换
  4. 如何使用grunt工具
  5. jackson 实体转json 为NULL或者为空不参加序列化
  6. javascript 判断浏览器的ie版本,替换html标签
  7. Counting Rectangles
  8. 汽车之家, 比亚迪等成为开源数据库SSDB的用户
  9. github上一些酷炫效果
  10. 自坑实录 - Asp.net MVC中无法使用@Ajax.BeginForm问题解决
  11. PHP 常量dirname(__file__)
  12. HTTP协议详解(四)
  13. 基于 debian 操作系统的 docker 镜像,安装 vim
  14. [转]Cordova - 彻底搞定IOS编译!
  15. 日志采集器windows客户端的配置释义
  16. android圆角功能,非常好用,可以用在图片,视频,gif等上面
  17. &quot;msg&quot;: &quot;Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host&#39;s fingerprint to your known_hosts file to ma
  18. 【读书笔记】iOS-网络-使用Bonjour实现自组织网络
  19. pycharm 2017注册码
  20. Exception in thread &quot;main&quot; java.lang.UnsatisfiedLinkError:

热门文章

  1. 沉淀,再出发——安装windows10和ubuntu kylin15.04双系统心得体会
  2. iOS——系统提供的dispatch方法
  3. uva 1583
  4. tcp/ip 卷一 读书笔记(3)为什么既要有IP地址又要有MAC地址
  5. 深刻理解iosBlock
  6. IDirectDraw接口
  7. jsp页面报错(一)
  8. LeetCode 456. 132 Pattern
  9. java暴力递归回溯算法
  10. 异常-----Template user.ftl not found