.Net Core微服务入门——NLog接入

26 篇文章 1 订阅
13 篇文章 1 订阅

.Net Core微服务入门——NLog接入

Nlog接入

1、引入NLog.Web.AspNetCore 包
在这里插入图片描述
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"
      throwConfigExceptions="true"
      internalLogLevel="Debug"
      internalLogToTrace="true">

	<targets>
		<target name="logfile"
				xsi:type="File"
				fileName="logs/${shortdate}.log"
				layout="${longdate} [${level:uppercase=true}] ${callsite:className=true:methodName=true:skipFrames=1} ${message} ${exception} @${callsite:fileName=true:includeSourcePath=true}" />
		<target name="console"
				xsi:type="ColoredConsole"
				layout="${longdate} [${level:uppercase=true}] ${callsite:className=true:methodName=true:skipFrames=1} ${message} ${exception} @${callsite:fileName=true:includeSourcePath=true}"/>
		<target xsi:type="Null" name="blackhole" />
	</targets>

	<rules>
		<!-- 除非调试需要,把 .NET Core 程序集的 Debug 输出都屏蔽 Trace -》Debug-》 Information -》Warning-》 Error-》 Critical-->
		<logger name="Microsoft.*" minLevel="Trace" writeTo="blackhole" final="true" />
		<!-- 除非调试需要,把系统的 Debug 输出都屏蔽 -->
		<logger name="System.*" minLevel="Trace" writeTo="blackhole" final="true" />

		<logger name="*" minlevel="Debug" writeTo="logfile,console" />
	</rules>
</nlog>

3、修改Program,注入NLog

public class Program
    {
        public static void Main(string[] args)
        {
            // 设置读取指定位置的nlog.config文件
            NLogBuilder.ConfigureNLog("XmlConfig/nlog.config");
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                // 配置使用NLog
                .UseNLog();
    }

4、增加日志共通处理类

public class LogHelper
    {
        private static readonly Logger log = LogManager.GetLogger("");
        public static void Error(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Error("#" + msg);
            else
                log.Error("#" + msg + "  " + exp.ToString());
        }

        public static void Debug(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Debug("#" + msg);
            else
                log.Debug("#" + msg + "  " + exp.ToString());
        }

        public static void Info(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Info("#" + msg);
            else
                log.Info("#" + msg + "  " + exp.ToString());
        }


        public static void Warn(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Warn("#" + msg);
            else
                log.Warn("#" + msg + "  " + exp.ToString());
        }
    }

5、记录日志

/// <summary>
/// 获取产品列表
/// </summary>
/// <returns>产品列表</returns>
[Route("GetAll")]
[HttpGet]
public List<Product> GetAllProducts() 
{
    LogHelper.Info("测试");
    var products = _context.Products.ToList<Product>();

    return products;
}

6、启动运行

调用接口,在执行目录下,发现日志文件

在这里插入图片描述
打开:

2021-08-24 03:13:15.4653 [INFO] MyAPI.Controllers.ProductsController.GetAllProducts #测试  @MyAPI.Common.LogHelper.Info(D:\Core\NetCoreFrame\MyAPI\Common\LogHelper.cs:32)

7、发布

调用接口,查看日志
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值