NLog日志

配置nlog

1.从nuget中获取配置

安装前2个文件

 然后会有一个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" throwExceptions="true">
  <targets xsi:type="AsyncWrapper">
    <!--保存至文件-->

    <!--
   {longdate}是长时间2017-08-09 235000
   {logger}获取的是命名空间和类
   {message}是记录信息
   {basedir}是项目所在地址
   {shortdate}短时间
   rchiveFilrName:是设置当文件达到一定大小值设定后 自动归档的文件名称
   archiveAboveSize: 是字节大小,(测试后发现的)
   archiveNumbering:归档文件方式 Rolling:递增,log1,log2
   concurrentWrites:是否允许使用通过多个进程的方式,将日志信息并行写入文件中
   keepFileOpen:保持文件一直开启,方便打开关闭等操作,提高性能
   maxArchiveFiles:设置归档文档的数量,默认9个
   -->
    <!--fileName="${basedir}/Logs/${shortdate}/${level:uppercase=false:padding=-5}.txt"
    layout="${shortdate} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />-->
    <target name="log_file" xsi:type="File"
             layout="${longdate} ${logger} ${message}"
            fileName="${basedir}/logs/logfile.txt"
            archiveFileName="${basedir}/archives/log.{#####}.txt"
            archiveAboveSize="1024"
            archiveNumbering="Rolling"
            concurrentWrites="false"
            keepFileOpen="true"
            maxArchiveFiles ="20"
                 />

    <!--输出至Debugger-->
    <target name="debugger" xsi:type="Debugger"
            layout="NLog: ${date:format=HH:mm:ss} | ${message}" />
    <!--输出至控制台-->
    <target name="console" xsi:type="ColoredConsole" layout="${longdate} ${message} ${exception:format=tostring}"></target>
    <!--输出至邮件-->
    <target xsi:type="Mail" name="infoMail"
         smtpServer="smtp.163.com"
         smtpPort="25"
         smtpAuthentication="Basic"
         smtpUserName="deno@163.com"
         smtpPassword="demo"
         enableSsl="true"
         addNewLines="true"
         from="demo@163.com"
         to="demo@qq.com"
         subject="Project Exception Mail"
         header="*********************"
         body="${longdate} | ${message} "
         footer="*********************"/>
  </targets>


  <rules>
    <!--将某个类的等级写到哪个日志里路由-->
    <logger name="*" level="Info" writeTo="log_file" />
    <logger name="*" level="Trace" writeTo="log_file" />
  </rules>
</nlog>

然后调用就可以了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NLogTest
{
    class Program
    {
        public static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            logger.Info("测试开始了你好都是发酵刷卡打飞机上岛咖啡地对地导弹多多多所发多所发所顶顶顶顶弟弟顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶多多多");
        }
    }
}

下载demo:

http://pan.baidu.com/s/1gfCet7X

原文地址:https://www.cnblogs.com/elsons/p/7610817.html