c# - TcpClient在tcp流关闭之前不会将数据发送到Logstash

标签 c# elasticsearch .net-core logstash tcpclient

我正在尝试通过TcpClient将数据写入logstash。代码工作正常,但是logstash仅显示最后发送的记录,并且仅在关闭tcp流之后显示。

_client = new TcpClient();
_client.Connect(_settings.Host, _settings.Port);
var stream = _client.GetStream();
stream.Write(encoded, 0, encoded.Length);
stream.Flush();

Logstash tcp设置:
input{
    tcp{
        type=>"app"
        port=>"9876"
    }
}

我怎么了错误的代码或错误的logstash设置

最佳答案

我知道这是一个旧帖子,但是想过为那些可能遇到相同问题的人发布解决方案。我认为,通过TCP将C#日志数据发送到LogStash的最简单方法如下。

#From logstash configs 
input{
  tcp{
    port=>"9876"
    codec=>"json"
  }
}

从C#方面,我们需要创建一个json字符串以发送到logstash。首先创建一个LogJson.cs类,并重写ToString()。此类将仅返回所需的格式化json字符串。
using System;
using Newtonsoft.Json;

namespace FeedLogstash
{
  class LogJson
  {
    public readonly int Id;
    public readonly DateTime DateTime;
    public readonly string Message;

    public LogJson(int id, DateTime dateTime, string message) {
        Id=id; DateTime=dateTime;  Message=message;
    }

    public override string ToString()  {
        return JsonConvert.SerializeObject(this);
    }
  }
}

现在,我们可以将上述json字符串发送到LogStash tcp输入。我正在使用C#SimpleTcpClient类创建简单连接。注意:您必须关闭连接才能写入数据。
using SimpleTCP;
...
public void PushData() {
  LogJson log = new LogJson(1001, DateTime.Now, "Danger: Will Robinson");
  SimpleTcpClient _client;
  _client = new SimpleTcpClient().Connect(host, port);
  _client.Write(log.ToString() + "\n");
  _client.Disconnect();
}

希望这对希望从C#通过TCP推送日志数据的人有所帮助。我相信Java可以采用相同的算法。

关于c# - TcpClient在tcp流关闭之前不会将数据发送到Logstash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51385958/

相关文章:

c# - 为绕过 token 触发 hCaptcha 回调函数

elasticsearch - Elasticsearch bool过滤器和minimum_should_match选项

elasticsearch - 如何删除elasticsearch中的index.routing.allocation.include.tag

c# - 获取用户定义程序集下的所有类型

c# - Application Insights 不显示 Trace.TraceInformation 消息

c# - CS0234 : The type or namespace name '<namespace2>' does not exist in the namespace '<namespace1>.' (are you missing an assembly reference? )

c# - 等待自定义函数

java - 在 Elasticsearch Java API 中将 _source 添加到 SearchQueryBuilder 的等效函数?

.net-core - Azure函数错误: BinaryFormatter serialization and deserialization are disabled within this application

c# - 使用 LINQ GroupBy() 从数据库获取唯一项目的强类型列表