当前位置:网站首页>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 Elastic、Seq 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
- Official documents Describes how to customize Target, Can be obtained a string Log message , Unable to get structured message
- 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}";
}
}
- 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 .
- establish WebApi project
- quote NLog.Target.MQTT

- 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>
- 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;
});
});
// ...
- 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()));
}
});
// ...
- 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();
// ...
- Real-time view log
visit index.html - 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 |
|---|---|
边栏推荐
- 今年的 618 不行了?
- 3M互助智能合约系统开发搭建技术
- rtmp webrtc 协议 openssl 等安装
- Pytest-- generate test report
- Alibaba cloud server + pagoda panel + no domain name deployment web project
- 机器学习模型监控(Aporia)
- 模板:P6114 【模板】Lyndon 分解&Runs(字符串)
- [1108. IP address invalidation]
- 力扣解法汇总1108-IP 地址无效化
- 剑指 Offer II 089. 房屋偷盗 / 剑指 Offer II 090. 环形房屋偷盗
猜你喜欢

Overseas new things | zoovu, an American AI startup, raised a new round of financing of US $169million to optimize the online "product discovery" experience for consumers

Pytest--生成测试报告

Yaml data driven demo

Unittest框架的测试日志

Design a print function to print the whole tree

机器学习中的概念漂移(Aporia)

Design and implementation of face verification system for floating population management

撰写有效帮助文档的7大秘诀

Test log of unittest framework

Pytest框架
随机推荐
Move Protocol Beta测试版稳定,临时决定奖池规模再扩大
The release of autok3s v0.5.0 continues to be simple and friendly
【SQLite】解决unrecognized token:“‘“
Pytest framework
建立自己的网站(11)
Serialization and deserialization of binary tree
使用PicGo-Core 和 阿里云 实现typora图片自动上传
Oracle JDBC Driver
【毕业N年系列】 毕业第四年
AutoK3s v0.5.0 发布 延续简约和友好
快速排序简单思路及程序
牛客网:验证IP地址
之前的装机记录
模板:P6114 【模板】Lyndon 分解&Runs(字符串)
撰写有效帮助文档的7大秘诀
[observation] Microsoft's "cloud + end" comprehensive innovation makes hybrid cloud simpler, more flexible and more secure
[ROS2 基础] Navigation2 导航系统介绍
机器学习模型监控(Aporia)
Google Earth engine (GEE) - sentinel-1 comprehensively check the difference between automatic landslide monitoring before and after two months (Guatemala as an example)
Postman基本操作
