在 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 中简单使用日志组件

[.Net Core] 在 Mvc 中简单使用日志组件的更多相关文章

  1. Asp.Net Core中简单使用日志组件log4net

    本文将简单介绍在.NET 6中使用log4net的方法,具体见下文范例. 1.首先新建一个ASP.NET Core空项目 2.通过Nuget包管理器安装下面两个包 log4net Microsoft. ...

  2. setbuffer和freopen做一个简单的日志组件

    目标场景是这样的: 多线程的应用程序要频繁打一些小字节的日志,也不想引用很重的日志库. 设想了一个极其简单的日志组件,main线程中重定向stdout到文件,同时setbuffer设置一个10k的缓冲 ...

  3. 使用SeasLog打造PHP项目中的高性能日志组件(一)

    云智慧(北京)科技有限公司 高驰涛 什么是SeasLog SeasLog是一个C语言编写的PHP扩展,提供一组规范标准的功能函数,在PHP项目中方便.规范.高效地写日志,以及快速地读取和查询日志. 为 ...

  4. [AspNetCore 3.0] 在RazorPages/MVC 中使用 Blazor (Razor组件)

    开发环境 Vs2019 16.3.1 dotnetcore 3.0 一.开始 新建webapp项目 dotnet new webapp -o projectname 或Vs 中新建项目选择 Web应用 ...

  5. 【ASP.NET Core】MVC中自定义视图的查找位置

    .NET Core 的内容处处可见,刷爆全球各大社区,所以,老周相信各位大伙伴已经看得不少了,故而,老周不考虑一个个知识点地去写,那样会成为年度最大的屁话,何况官方文档也很详尽.老周主要扯一下大伙伴们 ...

  6. MVC 中dapper的日志功能+程序报错修改

    由于之前的项目说最好要有日志功能,正好之前看过几篇这方面的文章就弄了点东西. 这是EF日志受启发很大的一个原文: http://www.cnblogs.com/GuZhenYin/p/5556732. ...

  7. mvc中简单的异常记录

    说明:异常处理 1.1 在WebApp的Model中 添加异常处理类 继承于HandleErrorAttribute using System; using System.Collections.Ge ...

  8. Asp.Net MVC中记录错误日志保存到本地txt文件

    为了方便查询系统出错弄个错误日志出来对于维护运维来说是很有必要的. 1.在Asp.Net MVC项目中的App_Start添加一个用于处理异常类的文件ErrorLog让他继承HandleErrorAt ...

  9. ASP.NET MVC中简单使用Autofac

    项目中引入Autofac的目的是为了实现控制反转,即IoC,Inversion of Control.控制反转可以有效的降低类之间的相互依赖关系,增加架构的弹性,降低软件复杂度. 示例代码: IPro ...

随机推荐

  1. HDU - 4496 City 逆向并查集

    思路:逆向并查集,逆向加入每一条边即可.在获取联通块数量的时候,直接判断新加入的边是否合并了两个集合,如果合并了说明联通块会减少一个,否则不变. AC代码 #include <cstdio> ...

  2. UVA 816 bfs

    算法入门经典上面的题.题目链接 uva816 大致题意 有一个最多包含9*9个交叉点的迷宫.输入起点.离开起点时的朝向和终点,求一条最短路(多解时任意输出一个即可).详细题意请看原题 思路 其实就是b ...

  3. HDU - 3567 IDA* + 曼哈顿距离 + 康托 [kuangbin带你飞]专题二

    这题难度颇大啊,TLE一天了,测试数据组数太多了.双向广度优先搜索不能得到字典序最小的,一直WA. 思路:利用IDA*算法,当前状态到达目标状态的可能最小步数就是曼哈顿距离,用于搜索中的剪枝.下次搜索 ...

  4. html标签详解

    html标签详解   <!DOCTYPE> 标签 <!DOCTYPE> 声明必须是 HTML 文档的第一行,位于 <html> 标签之前. <!DOCTYPE ...

  5. 3_Longest Substring Without Repeating Characters -- LeetCode

    C++解法一: class Solution { public: int lengthOfLongestSubstring(string s) { ] = {},left = , res = ; ; ...

  6. AutoAudit研究学习

    AutoAudit介绍   AutoAudit这个是Paul Nielsen写的一个开源的审计跟踪的脚本项目,项目位于https://autoaudit.codeplex.com/上,Paul Nie ...

  7. linux之x86裁剪移植---ffmpeg的H264解码显示(420、422)

    在虚拟机上yuv420可以正常显示 ,而945(D525)模块上却无法显示 ,后来验证了directdraw的yuv420也无法显示 ,由此怀疑显卡不支持 ,后把420转换为422显示. 420显示如 ...

  8. Linux显示文件和目录的详细资料

    Linux显示文件和目录的详细资料 youhaidong@youhaidong-ThinkPad-Edge-E545:~$ ls -l 总用量 56 -rw-r--r-- 1 youhaidong y ...

  9. java 后台封装json数据学习总结(一)

    一.数据封装 1. List集合转换成json代码 List list = new ArrayList(); list.add( "first" ); list.add( &quo ...

  10. python实现简单排序算法

    算法 递归两个特点: 调用自身 有穷调用 计算规模越来越小,直至最后结束 用装饰器修饰一个递归函数时会出现问题,这个问题产生的原因是递归的函数也不停的使用装饰器.解决方法是,只让装饰器调用一次即可,那 ...