http://nlog-project.org/2015/06/30/extending-nlog-is-easy.html

新建一个类库,命名规则为NLog.*.dll

定义一个类输出日志到RabbitMQ

    [Target("MQ")]
    public class MQTarget : TargetWithLayout
    {
        public MQTarget()
        {
        }
        public string Host { get; set; }

        public string UserName { get; set; }
        public string Password { get; set; }
        public string VirtualHost { get; set; }
        protected override void Write(LogEventInfo logEvent)
        {
            string message = this.Layout.Render(logEvent);
            SendMessageToMQ(Host,message);
        }
        private void SendMessageToMQ(string host,string message)
        {
            var factory = new ConnectionFactory() { HostName = Host,UserName= UserName, Password= Password, VirtualHost= VirtualHost};
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "apicenter",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                //string message = "Hello World!";
                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: "",
                                     routingKey: "apicenter",
                                     basicProperties: null,
                                     body: body);
                Console.WriteLine(" [x] Sent {0}", message);
            }

        }
    }

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="Logs\internal-nlog.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
    <add assembly="NLog.MQ"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="Logs\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="info" fileName="Logs\nlog-info-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <target xsi:type="File" name="error" fileName="Logs\nlog-error-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <target xsi:type="MQ" name="mq" host="10.202.80.196" UserName="bm" Password="bm_p@ss" VirtualHost="NIST"
            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="Info" 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="*" level="Info" writeTo="info" />

    <logger name="*" level="Error" writeTo="error" />
    <logger name="*" level="Error" writeTo="mq" />
  </rules>
</nlog>

这里需要注意一点,部署到Linux中的话,需要把nlog.config中的\ 替换成 /

Filter

定义一个日志记录sql

namespace LogExtension
{
    public class NLogSql
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public static void Info(string message)
        {
            logger.Info(message);
        }
    }
}

调用方法

public static void LogSql(string txt)
        {
            NLogSql.Info(txt);
        }

配置target

    <target xsi:type="File" name="sql" fileName="Logs/sql/nlog-sql-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <target xsi:type="File" name="info" fileName="Logs/info/nlog-info-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

配置rule

    <logger name="*" level="Info" writeTo="info" />
    <logger name="LogExtension.NLogSql" level="Info" writeTo="sql" />

这样日志不仅会写到sql文件中,也会写到info中

定义filter

    <logger name="*" level="Info" writeTo="info" >
      <filters>
        <when condition="equals(logger,'LogExtension.NLogSql')" action="Ignore"/>
      </filters>
    </logger>

这样就在info中排除了sql的日志。

File

Configuration File

<target xsi:type="
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

文件大小每超过1M就生成一个新的文件

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <!-- Log in a separate thread, possibly queuing up to
         messages. When the queue overflows, discard any
        extra messages-->

        <target name=" overflowAction="Discard">
            <target xsi:type="File" fileName="${basedir}/logs/${level}.txt" keepFileOpen="true" />
        </target>
    </targets>

    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

支持异步写文件

wrapper

https://github.com/nlog/nlog/wiki/Configuration-file#default-wrappers

https://github.com/nlog/nlog/wiki/Configuration-file#asynchronous-processing-and-wrapper-targets

NLog 自定义Target的更多相关文章

  1. NLog自定义Target之MQTT

    NLog是.Net中最流行的日志记录开源项目(之一),它灵活.免费.开源 官方支持文件.网络(Tcp.Udp).数据库.控制台等输出 社区支持Elastic.Seq等日志平台输出 实时日志需求 在工业 ...

  2. 转:NLog 自定义日志内容,写日志到数据库;修改Nlog.config不起作用的原因

    转:http://www.cnblogs.com/tider1999/p/4308440.html NLog的安装请百度,我安装的是3.2.NLog可以向文件,数据库,邮件等写日志,想了解请百度,这里 ...

  3. NLog自定义字段写入数据库表,示例

    //自定义字段写入NLog日志 private void saveNLog(InvokeLogModel model) { LogEventInfo ei = new LogEventInfo(); ...

  4. 为NLog自定义LayoutRenderer

    长话短说 前文<解剖HttpClientFactory,自由扩展HttpMessageHandler>主要想讲如何扩展HttpMessageHandler,  示例为在每个Http请求中的 ...

  5. NetCore2.2使用Nlog自定义日志写入路径配置方式

    在一些特定场景的业务需求下,日志需要写入到不同的路径下提供日志分析.第一种:默认Nlog可以通过日志级别来区分路径,——优点是不需要额外配置,开箱即用——缺点是不够灵活,如果超过级别数量,则不满足需求 ...

  6. NLog 自定义字段 写入 oracle

    1.通过Nuget安装NLog 下载,简单入门 请参照 我刚才转的几篇文章,下面我直接贴代码 2.建表语句 create table TBL_LOG ( id ) not null, appname ...

  7. [转]NLog 自定义字段 写入 oracle

    本文转自:http://www.cnblogs.com/skyapplezhao/p/5690695.html 1.通过Nuget安装NLog 下载,简单入门 请参照 我刚才转的几篇文章,下面我直接贴 ...

  8. 关于NLog的target和Layout

    这个没啥好说的,都是用别人的东西,看文档就行了,写的很详细. https://github.com/NLog/NLog/wiki/Configuration-file https://github.c ...

  9. NLog 安装使用

    1:安装 Install-Package NLog.Config 或 通过Nuget 2:Log levels Trace 非常详细的信息,一般在开发时使用. Debug 比Trace稍微少一点一般不 ...

随机推荐

  1. Mysql中存储引擎区别【 InnoDB、MyISAM】

    区别: 1. InnoDB支持事务,MyISAM不支持,对于InnoDB每一条SQL语言都默认封装成事务,自动提交,这样会影响速度,所以最好把多条SQL语言放在begin和commit之间,组成一个事 ...

  2. Java学习笔记day_01

    Java学习笔记(复习整理) 虽然不知道该怎么写,但是不起步就永远不知道该怎么做..刚开始可能会写的很差劲,但会一点一点变好的. 本笔记是以我按照传智播客的视频和Java核心思想来学习,前面的基础部分 ...

  3. STL之vector容器详解

    vector 容器 vector是C++标准模版库(STL,Standard Template Library)中的部分内容.之所以认为是一个容器,是因为它能够像容器一样存放各种类型的对象,简单的说: ...

  4. SpringMVC对静态资源的访问(js、css、img)

    在网上找了很多的内容,都没法解决,最后通过https://blog.csdn.net/wild46cat/article/details/52456715中内容解决的,在此记录一下. 项目结构: po ...

  5. Spring Boot Externalized Configuration

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html Ex ...

  6. 正则表达式校验yyyymmdd

    正则表达式为 ([\\d]{4}(((0[13578]|1[02])((0[1-9])|([12][0-9])|(3[01])))|(((0[469])|11)((0[1-9])|([12][1-9] ...

  7. POJ2947-Widget Factory

    工厂里每件期间的生产时间为3-9天,告诉你有N个器件和M个计划,每个计划都是说明生产1-N号器件的时间,最后问你每件器件的生产时间.或者多解或没有解. 例如样例 2 3 2 MON THU 1 2 3 ...

  8. Android开发者的Anko使用指南(四)之Layouts

    为什么不使用xml绘制Andoird的UI? 类型不安全 非空不安全 xml迫使你在很多布局中写很多相同的代码 设备在解析xml时会耗费更多的cpu运行时间和电池 最重要的时,它允许任何代码重用 简单 ...

  9. RabbitMQ 任务分发机制

    在上篇文章中,我们解决了从发送端(Producer)向接收端(Consumer)发送“Hello World”的问题.在实际的应用场景中,这是远远不够的.从本篇文章开始,我们将结合更加实际的应用场景来 ...

  10. day23_雷神_crm-day2

    # 俺滴第一个项目 CRM MdelForm 实现增删改查 1. ModelForm,重写 __init__ 方法,给所有字段添加 form-control 样式. 2. ModelForm,报错错误 ...