dotnet Core 学习(四):Logging

.net Core开发过程中日志记录非常的方便,只需要以下简单的几步操作就可以完成日志的输出:

1.引用类库

"Microsoft.Extensions.Logging": "1.1.0",
"Microsoft.Extensions.Logging.Console": "1.1.0",
"Microsoft.Extensions.Logging.Debug": "1.1.0"

2.简单的日志输出

  Console窗口输出:

public static void Main(string[] args)
        {
            ILoggerFactory logFactory=new LoggerFactory();                   //实例化日志工厂
            logFactory.AddConsole();                                         //添加日志输出至Console窗口
       logFactory.AddDebug();                                           //添加Debug输出
ILogger logger=logFactory.CreateLogger<Program>(); logger.LogInformation("TestLog"); Console.WriteLine("Hello World!"); }

  输出内容如下:

  

3.日志文件

   目前常用的日志工具Log4和NLog,好像只有Nlog首先支持了.NetCore。

   在项目中引用NLog类库:

"NLog.Extensions.Logging": "1.0.0-rtm-alpha4"

   并新增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">
  <targets>
    <!-- write logs to file -->
     <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
                 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />


    <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log"
             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />
  </targets>

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

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

 在代码中新增Nlog:

public static void Main(string[] args)
        {
            ILoggerFactory logFactory=new LoggerFactory();                   //实例化日志工厂
            logFactory.AddConsole();                                         //添加日志输出至Console窗口
            logFactory.AddDebug();                                           //添加Debug输出
            logFactory.AddNLog();
            ILogger logger=logFactory.CreateLogger<Program>();
            logger.LogInformation("TestLog");
            Console.WriteLine("Hello World!");
        }

 

转载于:https://www.cnblogs.com/leizhanjun/p/6109685.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值