Пример #1
0
        /// <summary>
        /// Connect to ElasticSearch server, before connected all log entries will be catched in queue
        /// </summary>
        /// <param name="url"></param>
        public static void ConnectElasticSearch(string url = "http://localhost:9200/")
        {
            var node = new Uri(url);
            var config = new ConnectionConfiguration(node)
                                .EnableTrace(false)
                                .EnableMetrics(false)
                                .UsePrettyRequests(false)
                                .UsePrettyResponses(false);

            client = new ElasticsearchClient(config);
            consoleOnly = false;

            CancellationToken ct = stopToken.Token;
            Task taskConsumeQueue = Task.Run(() =>
            {
                while (true)
                {
                    // Bulk insert cached logs every 1 second
                    while (logEntries.IsEmpty)
                    {
                        System.Threading.Thread.Sleep(1000);

                        // <- Stop()
                        if (ct.IsCancellationRequested)
                        {
                            return;
                        }
                    }

                    int batchLength = 0;
                    var builder = new StringBuilder();
                    var timestamp = "logger-" + DateTime.UtcNow.ToString("yyyy-MM-dd");
                    var indexOp = "{ \"index\" : { \"_index\" : \"" + timestamp + "\", \"_type\" : \"log\" } }";
                    while (logEntries.IsEmpty == false && batchLength < 100)
                    {
                        JObject entry;
                        if (logEntries.TryDequeue(out entry))
                        {
                            builder.AppendLine(indexOp);
                            builder.AppendLine(entry.ToString(Formatting.None));
                            batchLength++;
                        }
                    }
                    if (batchLength > 0)
                        client.BulkAsync(builder.ToString());
                }
            });
        }