< Summary

Class:SVETA.Api.Helpers.ElasticCollector
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Helpers/ElasticCollector.cs
Covered lines:0
Uncovered lines:41
Coverable lines:41
Total lines:65
Line coverage:0% (0 of 41)
Covered branches:0
Total branches:4
Branch coverage:0% (0 of 4)

Metrics

MethodLine coverage Branch coverage
get_ServiceName()0%100%
get_CollectorUrl()0%100%
.ctor(...)0%0%
Emit()0%100%
CreateContent(...)0%100%

File(s)

/opt/dev/sveta_api_build/SVETA.Api/Helpers/ElasticCollector.cs

#LineLine coverage
 1using System;
 2using System.Net.Http;
 3using System.Text;
 4using System.Threading.Tasks;
 5using Newtonsoft.Json;
 6using Newtonsoft.Json.Converters;
 7using Newtonsoft.Json.Serialization;
 8using Serilog.Core;
 9using Serilog.Events;
 10
 11namespace SVETA.Api.Helpers
 12{
 13    public class ElasticCollector: ILogEventSink
 14    {
 15        private readonly IFormatProvider _formatProvider;
 16        private readonly HttpClient _httpClient;
 17
 018        public string ServiceName { get; set; }
 019        public string CollectorUrl { get; set; }
 20
 021        public ElasticCollector(string collectorUrl,
 022            string serviceName,
 023            IFormatProvider formatProvider)
 024        {
 025            _formatProvider = formatProvider;
 026            _httpClient = new HttpClient();
 027            if (string.IsNullOrEmpty(collectorUrl))
 028                collectorUrl = "http://localhost";
 029            if (!collectorUrl.StartsWith("http"))
 030            {
 031                collectorUrl = "http://" + collectorUrl;
 032            }
 033            CollectorUrl = collectorUrl;
 034            ServiceName = serviceName;
 035        }
 36        public async void Emit(LogEvent logEvent)
 037        {
 038            var message = logEvent.RenderMessage(_formatProvider);
 039            var content = CreateContent(new {Service = ServiceName, Message = message});
 40            try
 041            {
 042                _httpClient.PostAsync(CollectorUrl, content);
 043            }
 044            catch (Exception e)
 045            {
 046                Console.WriteLine(DateTimeOffset.Now.ToString() + " " + message);
 047            }
 048        }
 49        private static StringContent CreateContent(object body)
 050        {
 051            var serializeSettings = new JsonSerializerSettings
 052            {
 053                ContractResolver = new CamelCasePropertyNamesContractResolver()
 054            };
 055            serializeSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-ddTHH:mm:ss" });
 056            var res = JsonConvert.SerializeObject(body, serializeSettings);
 057            var cont = new StringContent(
 058                res,
 059                Encoding.UTF8,
 060                "application/json");
 061            return cont;
 062        }
 63    }
 64
 65}