当前位置:网站首页>Mqtt of NLog custom target

Mqtt of NLog custom target

2022-06-21 17:22:00 Liziti

High quality resource sharing

Learning route guidance ( Click unlock ) Knowledge orientation Crowd positioning
🧡 Python Actual wechat ordering applet 🧡 Progressive class This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system .
Python Quantitative trading practice beginner Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system

NLog yes .Net in Most popular Logging open source projects ( One of ), it flexible free Open source

Official support file The Internet (Tcp、Udp)、 database Console Equal output

Community support ElasticSeq Wait for the log platform to output

Real time log requirements

In specific scenarios such as the industrial Internet of things Get logs in real time Information

Commonly used in the field of industrial Internet of things is mqtt agreement

Then we use NLog Customize a Target, Output log to MqttServer

Web adopt Mqtt(websocket) Get logs in real time , and No The passage of tradition WebApi polling journal

NLog Customize Target

  1. Official documents Describes how to customize Target, Can be obtained a string Log message , Unable to get structured message
  2. Use custom when needed Field To do this part of the job
/// 
/// Additional field details
/// 
[NLogConfigurationItem]
public class Field
{
    /// 
    /// Name of additional field
    /// 
    [RequiredParameter]
    public string Name { get; set; }

    /// 
    /// Value with NLog  rendering support
    /// 
    [RequiredParameter]
    public Layout Layout { get; set; }

    /// 
    /// Custom type conversion from default string to other type
    /// 
    /// 
    ///  can be used if the  renders JSON
    /// 
    public Type LayoutType { get; set; } = typeof(string);

    /// 
    public override string ToString()
    {
        return $"Name: {Name}, LayoutType: {LayoutType}, Layout: {Layout}";
    }
}

  1. rewrite Write Method
protected override void Write(LogEventInfo logEvent)
{
    //default fields
    Dictionary<string, object> logDictionary = new()
    {
        { "timestamp", logEvent.TimeStamp },
        { "level", logEvent.Level.Name },
        { "message", RenderLogEvent(Layout, logEvent) }
    };

    //customer fields
    // Here it is treated as a string , There's room for optimization 
    foreach (var field in Fields)
    {
        var renderedField = RenderLogEvent(field.Layout, logEvent);

        if (string.IsNullOrWhiteSpace(renderedField))
            continue;

        logDictionary[field.Name] = renderedField;
    }

    SendTheMessage2MqttBroker(JsonConvert.SerializeObject(logDictionary));
}

Use

The following will be used Nlog.Target.MQTT, Demonstrated through web Real-time view Application's journal .

  1. establish WebApi project
  2. quote NLog.Target.MQTT

  1. The configuration file
<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
    
    <add assembly="NLog.Targets.MQTT"/>
extensions>


<targets>
    
    <target xsi:type="MQTT" name="mqtt" host="localhost" port="1883" username="UserName" password="Password" topic="log"
 layout="${longdate}|${event-properties:item=EventId\_Id:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" >
        <field name="machine" layout="${machinename}" />
        <field name="processid" layout="${processid}" />
        <field name="threadname" layout="${threadname}" />
        <field name="logger" layout="${logger}" />
        <field name="callsite" layout="${callsite-linenumber}" />
        <field name="url" layout="${aspnet-request-url}" />
        <field name="action" layout="${aspnet-mvc-action}" />
        <field name="level" layout="${level:uppercase=true}" />
        <field name="message" layout="${message}" />
        <field name="exception" layout="${exception:format=toString}" />
    target>
targets>


<rules>
    <logger name="*" minlevel="Trace" writeTo="mqtt" />
rules>

  1. To configure MQTTServer and NLog
// ...
// NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.Host.UseNLog();

//AddHostedMqttServer
builder.Services.AddHostedMqttServer(mqttServer =>
    {
        mqttServer.WithoutDefaultEndpoint();
    })
    .AddMqttConnectionHandler()
    .AddConnections();

//Config Port
builder.WebHost.UseKestrel(option =>
{
    option.ListenAnyIP(1883, l => l.UseMqtt());
    option.ListenAnyIP(80);
});
var app = builder.Build();

// ...
//UseStaticFiles html js etc.
app.UseStaticFiles();
app.UseRouting();

//Websocket Mqtt
app.UseEndpoints(endpoints =>
{
    //MqttServerWebSocket
    endpoints.MapConnectionHandler("/mqtt", options =>
 {
 options.WebSockets.SubProtocolSelector = MqttSubProtocolSelector.SelectSubProtocol;
 });
});
// ...

  1. Web Connect MqttServer
// ... 
"./jquery.min.js"</span>>
<script src="./mqtt.min.js">script>
<script src="./vue.js">script>
// ...

var client = mqtt.connect('ws://' + window.location.host + '/mqtt', options);
client.on('connect',
    function() {
        client.subscribe('log',
            function(err) {
                if (!err) {
                    console.log("subed!");
                } else {
                    alert("subed error!");
                }
            });
    });
client.on('message',
    function(topic, message) {
        if (topic === 'log') {
            if (app.logs.length > 50)
                app.logs.length = 0;
            app.logs.unshift($.parseJSON(message.toString()));
        }
    });
// ...

  1. Output log
// ... 
_logger.LogDebug("LogDebug!");
_logger.LogError(new Exception("Exception Message!"), "LogError!");

//new thread output log after 500ms
Thread thread = new Thread(ThreadProc);
thread.Name = "My Thread";
thread.Start();
// ...

  1. Real-time view log
    visit index.html
  2. adopt Mqtt Client subscription log

Source code

ad locum NLog.Targets.MQTT:https://github.com/iioter/NLog.Targets.MQTT

Related links

[1] NLog.Targets.MQTT:https://github.com/iioter/NLog.Targets.MQTT

[2] IoTGateway-Doc:http://iotgateway.net/blog/NLog

[3] NLog Customize Target:https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target

communication

official account : Industrial Internet of things gateway QQ Group :712105424
原网站

版权声明
本文为[Liziti]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211402226830.html