private T Search <T>(string endPoint, IDictionary <string, object> parameters)
            where T : class
        {
            try
            {
                var searchPathAndQuery = GetUrl(endPoint, parameters);

                using (var response = _httpClient.GetAsync(searchPathAndQuery).Result)
                {
                    var isFieldResponseResultExpected = typeof(T) == typeof(FieldResponse);
                    var responseBody = response.Content.ReadAsStringAsync().Result;
                    if (response.IsSuccessStatusCode)
                    {
                        T responseObject = isFieldResponseResultExpected
                            ? new FieldResponse(JObject.Parse(responseBody), parameters["fieldname"].ToString()) as T
                            : JsonConvert.DeserializeObject <T>(responseBody);

                        var responseAsSearchResponseBase = responseObject as SearchResponseBase;
                        if (responseAsSearchResponseBase != null)
                        {
                            responseAsSearchResponseBase.Transport = this;
                        }

                        return(responseObject);
                    }
                    LogglyException.Throw(responseBody);
                    return(null);
                }
            }
            catch (Exception ex)
            {
                LogglyException.Throw(ex, ex.Message);
                return(null);
            }
        }
Exemple #2
0
        public async Task <LogResponse> Send(IEnumerable <LogglyMessage> messages)
        {
            var logResponse = new LogResponse();

            if (LogglyConfig.Instance.IsValid)
            {
                var list = messages.ToList();

                using (var response = await PostUsingHttpClient(list).ConfigureAwait(false))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        logResponse = new LogResponse {
                            Code = ResponseCode.Success
                        };
                    }
                    else
                    {
                        logResponse = new LogResponse {
                            Code = ResponseCode.Error, Message = "Loggly returned status:" + response.StatusCode
                        };
                    }
                }
                foreach (var m in list)
                {
                    LogglyEventSource.Instance.Log(m, logResponse);
                }
            }
            else
            {
                LogglyException.Throw("Loggly configuration is missing or invalid. Did you specify a customer token?");
            }
            return(logResponse);
        }
        private Task <HttpResponseMessage> PostUsingHttpClient(List <LogglyMessage> messages)
        {
            string tags;

            if (messages.Count == 1)
            {
                tags = GetRenderedTags(messages[0].CustomTags);
            }
            else
            {
                // if bulk sending messages, send all tags which have the same value for all messages
                tags = string.Join(",", messages.SelectMany(x => GetLegalTagUnion(x.CustomTags)).GroupBy(x => x).Where(x => x.Count() == messages.Count).Select(x => x.Key));
            }

            var request = new HttpRequestMessage(HttpMethod.Post, messages.Count == 1 ? UrlSingle : UrlBulk);

            if (!string.IsNullOrEmpty(tags))
            {
                request.Headers.Add("X-LOGGLY-TAG", tags);
            }
            var type = messages.First().Type;

            if (!messages.TrueForAll(x => type == x.Type))
            {
                LogglyException.Throw("Cannot have mixed Plain and Json messages");
            }

            string messageContent;

            if (messages.Count == 1)
            {
                messageContent = messages[0].Content;
            }
            else
            {
                var builder = new StringBuilder(messages[0].Content);
                for (var i = 1; i < messages.Count; i++)
                {
                    builder.Append('\n');
                    builder.Append(messages[i].Content);
                }
                messageContent = builder.ToString();
            }

            StringContent postData = null;

            switch (type)
            {
            case MessageType.Plain:
                postData = new StringContent(messageContent, Encoding.UTF8, "text/plain");
                break;

            case MessageType.Json:
                postData = new StringContent(messageContent, Encoding.UTF8, "application/json");
                break;
            }

            request.Content = postData;
            return(HttpClient.SendAsync(request));
        }
Exemple #4
0
        private async Task <LogResponse> LogWorker(LogglyEvent[] events)
        {
            try
            {
                if (LogglyConfig.Instance.IsEnabled)
                {
                    if (LogglyConfig.Instance.Transport.LogTransport == LogTransport.Https)
                    {
                        if (!LogglyConfig.Instance.Transport.IsOmitTimestamp)
                        {
                            foreach (var e in events)
                            {
                                // syslog has this data in the header, only need to add it for Http
                                e.Data.AddIfAbsent("timestamp", e.Timestamp);
                            }
                        }
                    }

                    return(await _transport.Send(events.Select(BuildMessage)).ConfigureAwait(false));
                }
                else
                {
                    return(new LogResponse {
                        Code = ResponseCode.SendDisabled
                    });
                }
            }
            catch (Exception e)
            {
                LogglyException.Throw(e);
                return(new LogResponse {
                    Code = ResponseCode.Unknown
                });
            }
        }
        public LogResponse Send(LogglyMessage message)
        {
            var logResponse = new LogResponse();

            if (LogglyConfig.Instance.IsValid)
            {
                var httpWebRequest = CreateHttpWebRequest(message);

                using (var response = httpWebRequest.GetResponse())
                {
                    var rawResponse = Response.CreateSuccess(GetResponseBody(response));

                    if (rawResponse.Success)
                    {
                        logResponse      = JsonConvert.DeserializeObject <LogResponse>(rawResponse.Raw);
                        logResponse.Code = ResponseCode.Success;
                    }
                    else
                    {
                        logResponse = new LogResponse {
                            Code = ResponseCode.Error, Message = rawResponse.Error.Message
                        };
                    }
                }
            }
            else
            {
                LogglyException.Throw("Loggly configuration is missing or invalid. Did you specify a customer token?");
            }
            LogglyEventSource.Instance.Log(message, logResponse);
            return(logResponse);
        }
Exemple #6
0
        private HttpWebRequest CreateHttpWebRequest(List <LogglyMessage> message)
        {
            var httpWebRequest = CreateHttpWebRequest(message.Count == 1 ? UrlSingle : UrlBulk, HttpRequestType.Post);

            // if bulk sending messages, what do we do with unique tags per message? For now ignore them
            var tags = GetRenderedTags(message.Count == 1 ? message[0].CustomTags : new List <ITag>());

            if (!string.IsNullOrEmpty(tags))
            {
                httpWebRequest.Headers.Add("X-LOGGLY-TAG", tags);
            }
            var type = message.First().Type;

            if (!message.TrueForAll(x => type == x.Type))
            {
                LogglyException.Throw("Cannot have mixed Plain and Json messages");
            }

            switch (type)
            {
            case MessageType.Plain:
                httpWebRequest.ContentType = "content-type:text/plain";
                break;

            case MessageType.Json:
                httpWebRequest.ContentType = "application/json";
                break;
            }
            var  builder = new StringBuilder();
            bool isFirst = true;

            foreach (var m in message)
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    builder.Append('\n');
                }
                builder.Append(m.Content);
            }
            var contentBytes = Encoding.UTF8.GetBytes(builder.ToString());

            httpWebRequest.ContentLength = contentBytes.Length;

            using (var requestStream = httpWebRequest.GetRequestStream())
            {
                requestStream.Write(contentBytes, 0, contentBytes.Length);
                requestStream.Flush();
                requestStream.Close();
            }

            return(httpWebRequest);
        }
        private Task <HttpResponseMessage> PostUsingHttpClient(List <LogglyMessage> messages)
        {
            string tags = GetRenderedTags(messages);

            var request = new HttpRequestMessage(HttpMethod.Post, messages.Count == 1 ? UrlSingle : UrlBulk);

            if (!string.IsNullOrEmpty(tags))
            {
                request.Headers.Add("X-LOGGLY-TAG", tags);
            }

            var type = messages.First().Type;

            foreach (var msg in messages)
            {
                if (msg.Type != type)
                {
                    LogglyException.Throw("Cannot have mixed Plain and Json messages");
                }
            }

            string messageContent;

            if (messages.Count == 1)
            {
                messageContent = messages[0].Content;
            }
            else
            {
                var builder = new StringBuilder(messages[0].Content);
                for (var i = 1; i < messages.Count; i++)
                {
                    builder.Append('\n');
                    builder.Append(messages[i].Content);
                }
                messageContent = builder.ToString();
            }

            StringContent postData = null;

            switch (type)
            {
            case MessageType.Plain:
                postData = new StringContent(messageContent, Encoding.UTF8, "text/plain");
                break;

            case MessageType.Json:
                postData = new StringContent(messageContent, Encoding.UTF8, "application/json");
                break;
            }

            request.Content = postData;
            return(HttpClient.SendAsync(request));
        }
        private Task <HttpResponseMessage> PostUsingHttpClient(HttpClient httpClient, List <LogglyMessage> message)
        {
            // if bulk sending messages, what do we do with unique tags per message? For now ignore them
            var tags = GetRenderedTags(message.Count == 1 ? message[0].CustomTags : new List <ITag>());

            if (!string.IsNullOrEmpty(tags))
            {
                httpClient.DefaultRequestHeaders.Add("X-LOGGLY-TAG", tags);
            }
            var type = message.First().Type;

            if (!message.TrueForAll(x => type == x.Type))
            {
                LogglyException.Throw("Cannot have mixed Plain and Json messages");
            }

            var  builder = new StringBuilder();
            bool isFirst = true;

            foreach (var m in message)
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    builder.Append('\n');
                }
                builder.Append(m.Content);
            }

            StringContent postData = null;

            switch (type)
            {
            case MessageType.Plain:
                postData = new StringContent(builder.ToString(), Encoding.UTF8, "text/plain");
                break;

            case MessageType.Json:
                postData = new StringContent(builder.ToString(), Encoding.UTF8, "application/json");
                break;
            }

            return(httpClient.PostAsync(message.Count == 1 ? UrlSingle : UrlBulk, postData));
        }
        private T Search <T>(string endPoint, IDictionary <string, object> parameters)
            where T : class
        {
            try
            {
                var searchPathAndQuery = GetUrl(endPoint, parameters);
                using (var httpClient = CreateHttpClient(HttpRequestType.Get))
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                        "Basic",
                        Convert.ToBase64String(
                            Encoding.ASCII.GetBytes(
                                string.Format("{0}:{1}", _config.Username, _config.Password))));

                    using (var response = httpClient.GetAsync(searchPathAndQuery).Result)
                    {
                        var isFieldResponseResultExpected = typeof(T) == typeof(FieldResponse);
                        var responseBody = GetResponseBody(response);
                        if (response.IsSuccessStatusCode)
                        {
                            T responseObject = isFieldResponseResultExpected
                                ? new FieldResponse(JObject.Parse(responseBody), parameters["fieldname"].ToString()) as T
                                : JsonConvert.DeserializeObject <T>(responseBody);

                            var responseAsSearchResponseBase = responseObject as SearchResponseBase;
                            if (responseAsSearchResponseBase != null)
                            {
                                responseAsSearchResponseBase.Transport = this;
                            }

                            return(responseObject);
                        }
                        else
                        {
                            LogglyException.Throw(GetResponseBody(response));
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogglyException.Throw(ex, ex.Message);
                return(null);
            }
        }
Exemple #10
0
        private async Task <LogResponse> LogWorker(LogglyEvent[] events)
        {
            var response = new LogResponse {
                Code = ResponseCode.Unknown
            };

            try
            {
                if (LogglyConfig.Instance.IsEnabled)
                {
                    if (LogglyConfig.Instance.Transport.LogTransport == LogTransport.Https)
                    {
                        if (!LogglyConfig.Instance.Transport.IsOmitTimestamp)
                        {
                            foreach (var e in events)
                            {
                                // syslog has this data in the header, only need to add it for Http
                                e.Data.AddIfAbsent("timestamp", e.Timestamp);
                            }
                        }
                    }

                    IMessageTransport transporter = TransportFactory();
                    response = await transporter.Send(events.Select(x => new LogglyMessage
                    {
                        Timestamp  = x.Timestamp,
                        Syslog     = x.Syslog,
                        Type       = MessageType.Json,
                        Content    = ToJson(x.Data),
                        CustomTags = x.Options.Tags
                    })).ConfigureAwait(false);
                }
                else
                {
                    response = new LogResponse {
                        Code = ResponseCode.SendDisabled
                    };
                }
            }
            catch (Exception e)
            {
                LogglyException.Throw(e);
            }
            return(response);
        }
Exemple #11
0
        private LogResponse LogWorker(LogglyEvent logglyEvent)
        {
            var response = new LogResponse {
                Code = ResponseCode.Unknown
            };

            try
            {
                if (LogglyConfig.Instance.IsEnabled)
                {
                    if (LogglyConfig.Instance.Transport.LogTransport == LogTransport.Https)
                    {
                        // syslog has this data in the header, only need to add it for Http
                        logglyEvent.Data.AddIfAbsent("timestamp", logglyEvent.Timestamp);
                    }

                    var message = new LogglyMessage
                    {
                        Timestamp = logglyEvent.Timestamp
                        , Syslog  = logglyEvent.Syslog
                        , Type    = MessageType.Json
                        , Content = ToJson(logglyEvent.Data)
                    };

                    IMessageTransport transporter = TransportFactory();
                    response = transporter.Send(message);
                }
                else
                {
                    response = new LogResponse {
                        Code = ResponseCode.SendDisabled
                    };
                }
            }
            catch (Exception e)
            {
                LogglyException.Throw(e);
            }
            return(response);
        }
Exemple #12
0
        private T Search <T>(string endPoint, IDictionary <string, object> parameters)
            where T : class
        {
            try
            {
                var searchPathAndQuery = GetUrl(endPoint, parameters);
                var searchRequest      = CreateHttpWebRequest(searchPathAndQuery, HttpRequestType.Get);

                searchRequest.Credentials = new NetworkCredential(_config.Username, _config.Password);

                using (var response = searchRequest.GetResponse())
                {
                    var isFieldResponseResultExpected = typeof(T) == typeof(FieldResponse);
                    var responseBody   = GetResponseBody(response);
                    T   responseObject = isFieldResponseResultExpected
                        ? new FieldResponse(JObject.Parse(responseBody), parameters["fieldname"].ToString()) as T
                        : JsonConvert.DeserializeObject <T>(responseBody);

                    var responseAsSearchResponseBase = responseObject as SearchResponseBase;
                    if (responseAsSearchResponseBase != null)
                    {
                        responseAsSearchResponseBase.Transport = this;
                    }

                    return(responseObject);
                }
            }
            catch (WebException ex)
            {
                LogglyException.Throw(ex, GetResponseBody(ex.Response));
                return(null);
            }
            catch (Exception ex)
            {
                LogglyException.Throw(ex, ex.Message);
                return(null);
            }
        }
        public async Task <LogResponse> Send(IEnumerable <LogglyMessage> messages)
        {
            var logResponse = new LogResponse();

            if (LogglyConfig.Instance.IsValid)
            {
                var list = messages.ToList();
                using (var httpClient = CreateHttpClient(HttpRequestType.Post))
                {
                    using (var response = await PostUsingHttpClient(httpClient, list).ConfigureAwait(false))
                    {
                        var rawResponse = Response.CreateSuccess(GetResponseBody(response));

                        if (rawResponse.Success)
                        {
                            logResponse      = JsonConvert.DeserializeObject <LogResponse>(rawResponse.Raw);
                            logResponse.Code = ResponseCode.Success;
                        }
                        else
                        {
                            logResponse = new LogResponse {
                                Code = ResponseCode.Error, Message = rawResponse.Error.Message
                            };
                        }
                    }
                    foreach (var m in list)
                    {
                        LogglyEventSource.Instance.Log(m, logResponse);
                    }
                }
            }
            else
            {
                LogglyException.Throw("Loggly configuration is missing or invalid. Did you specify a customer token?");
            }
            return(logResponse);
        }