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;
        }
        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;
        }
        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;
        }
        public async Task<LogResponse> Send(IEnumerable<LogglyMessage> messages)
        {
            var logResponse = new LogResponse();

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

                using (var response = await httpWebRequest.GetResponseAsync().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;
        }
        public async Task<LogResponse> Send(IEnumerable<LogglyMessage> messages)
        {
            foreach (var message in messages)
            {
                var sysLog = ConstructSyslog(message);
                await Send(sysLog);

                var response = new LogResponse
                {
                    Code = ResponseCode.AssumedSuccess
                };
                LogglyEventSource.Instance.Log(message, response);
            }

            return new LogResponse
            {
                Code = ResponseCode.AssumedSuccess
            };
        }
Esempio n. 6
0
        protected virtual async Task <LogResponse> LoginAsync(IConnect helper)
        {
            LogResponse res = new LogResponse(true, "登录成功");

            if (helper != null)
            {
                if (Settings.EnableRelogin)
                {
                    await helper.LogoutAsync();
                }
                var r = await helper.LoginAsync();

                if (!r.Succeed)
                {
                    res = r;
                }
            }
            await RefreshAsync(helper);

            return(res);
        }
Esempio n. 7
0
        private static void OnReceive([CanBeNull] Message message)
        {
            if (message == null)
            {
                return;
            }

            LogResponse logResponse = message as LogResponse;

            if (logResponse != null &&
                logResponse.Logs != null)
            {
                ConsoleTextWriter.Default.Context.Invoke(
                    () =>
                {
                    if (Console.CursorLeft != 0)
                    {
                        ConsoleTextWriter.Default.WriteLine();
                    }
                    foreach (Log log in logResponse.Logs)
                    {
                        Debug.Assert(log != null);
                        log.WriteTo(ConsoleTextWriter.Default, _logFormatBuilder);
                    }
                });

                return;
            }

            DisconnectResponse disconnectResponse = message as DisconnectResponse;

            if (disconnectResponse == null)
            {
                return;
            }
            ConsoleTextWriter.Default.WriteLine();
            ConsoleTextWriter.Default.WriteLine("Disconnected");
        }
Esempio n. 8
0
        public async Task Invoke(HttpContext context)
        {
            var bodyStream = context.Response.Body;

            var responseBodyStream = new MemoryStream();

            context.Response.Body = responseBodyStream;

            await _next(context);

            responseBodyStream.Seek(0, SeekOrigin.Begin);
            var responseBody = new StreamReader(responseBodyStream).ReadToEnd();
            // Save to database
            LogResponse r = new LogResponse();

            r.body    = responseBody;
            r.created = DateTime.UtcNow;
            dbcontext.Add(r);
            dbcontext.SaveChanges();

            responseBodyStream.Seek(0, SeekOrigin.Begin);
            await responseBodyStream.CopyToAsync(bodyStream);
        }
Esempio n. 9
0
        public async Task AsyncV3_Log_MultiThread()
        {
            // Arrange
            var logger   = new AsyncLoggerV3(_path);
            var expected = new LogResponse()
            {
                IsSuccess = true
            };

            // Act
            var tasks = Enumerable.Range(1, 100)
                        .Select(x => logger.LogAsync(String.Format(_logMessage, $"[Async3 {x}]")));

            var actual = await Task.WhenAll(tasks.ToArray());

            /**** Notice no additional work is needed to schedule/coordinate all threads ****/


            // Assert
            Assert.IsTrue(actual.Length == 100);         // Access to all 100 thread outcomes
            Assert.IsTrue(actual.All(a => a.IsSuccess)); // Checks that every task was successful
            Assert.IsTrue(File.Exists(_logFile));
        }
            public InvalidPayloadPersistenceTests()
            {
                var fsAdapter = Substitute.For <IFileSystemAdapter>();

                fsAdapter.When(x => x.WriteAllBytes(Arg.Any <string>(), Arg.Any <byte[]>()))
                .Do(x =>
                {
                    _generatedFilename = x.ArgAt <string>(0);
                    _writtenData       = _utf8Encoder.GetString(x.ArgAt <byte[]>(1));
                });


                //simulate the Post to Loggly failure with an error response and fixed payload.
                var response = new LogResponse {
                    Code = ResponseCode.Error, Message = "502 Bad Request"
                };
                //just need an empty event for testing
                var payload = new List <LogglyEvent>
                {
                    new LogglyEvent
                    {
                        Data    = new MessageData(),
                        Options = new EventOptions(),
                        Syslog  = new SyslogHeader()
                        {
                            MessageId = 0
                        },
                        Timestamp = DateTimeOffset.Parse("2017-09-27T00:00:00+00:00")   //fixed date for comparisson
                    }
                };

                var instance = new InvalidPayloadLogger(LogFolder, _utf8Encoder, fsAdapter);

                //exercice the method
                instance.DumpInvalidPayload(response, payload);
            }
 public virtual void Insert(LogResponse entity)
 {
     dbSet.Add(entity);
     context.SaveChanges();
 }
Esempio n. 12
0
 public async Task <LogResponse> LoginAsync(IPAddress ip) => LogResponse.ParseFromUsereg(await PostAsync(ConnectUri, new Dictionary <string, string>
 {
     ["user_ip"] = ip.ToString(),
     ["drop"]    = "0"
 }));
        public void Constructor_InitializesResponseCodeProperty()
        {
            var response = new LogResponse(MessageResponseCode.Success);

            Assert.Equal(MessageResponseCode.Success, response.ResponseCode);
        }
Esempio n. 14
0
 public async Task <LogResponse> LogoutAsync() => LogResponse.ParseFromUsereg(await PostAsync(LogUri, LogoutData));
Esempio n. 15
0
 public async Task <LogResponse> LogoutAsync(IPAddress ip) => LogResponse.ParseFromUsereg(await PostAsync(InfoUri, string.Format(DropData, ip.ToString())));
        private async Task <string> DoRequest(string methodString, HttpRequestMethod requestMethod, string postData = null)
        {
            // make sure values are set
            if (string.IsNullOrEmpty(this.URL))
            {
                throw new InvalidOperationException("URL not set");
            }
            if (string.IsNullOrEmpty(this.apiKey))
            {
                throw new InvalidOperationException("apiKey not set");
            }
            if (string.IsNullOrEmpty(this.Password))
            {
                throw new InvalidOperationException("Password not set");
            }

            // create the URI
            string addressString = string.Format("{0}{1}", this.URL, (this.URL.EndsWith("/") ? string.Empty : "/"));

            var uriBuilder = new UriBuilder(addressString)
            {
                Scheme = "https",
                Port   = -1 // default port for scheme
            };
            Uri address = uriBuilder.Uri;

            var handler = new HttpClientHandler();

            handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            var client = new HttpClient(handler)
            {
                Timeout     = TimeSpan.FromMilliseconds(this._timeout),
                BaseAddress = address
            };

            var byteArray = Encoding.ASCII.GetBytes($"{this.apiKey}:{this.Password}");

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            client.DefaultRequestHeaders.Add("User-Agent", UserAgent);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(this.UseJSON ? "application/json" : "application/xml"));
            client.DefaultRequestHeaders.TransferEncodingChunked = false;

            try
            {
                // Send the request for logging, if applicable.
                LogRequest?.Invoke(requestMethod, addressString + methodString, postData);

                switch (requestMethod)
                {
                case HttpRequestMethod.Get:
                    _lastResponse = await client.GetAsync(methodString);

                    break;

                case HttpRequestMethod.Post:
                    _lastResponse = await client.PostAsync(methodString, new StringContent(postData, Encoding.UTF8, this.UseJSON ? "application/json" : "text/xml"));

                    break;

                case HttpRequestMethod.Put:
                    _lastResponse = await client.PutAsync(methodString, new StringContent(postData, Encoding.UTF8, this.UseJSON ? "application/json" : "text/xml"));

                    break;

                case HttpRequestMethod.Delete:
                    _lastResponse = await client.DeleteAsync(methodString);

                    break;
                }

                var content = await _lastResponse?.Content?.ReadAsStringAsync();

                // Send the response for logging, if applicable.
                LogResponse?.Invoke(_lastResponse.StatusCode, addressString + methodString, content);

                return(content);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 17
0
 public void Log(string message, bool json, Action<LogResponse> callback)
 {
     var communicator = new Communicator(this);
      var callbackWrapper = callback == null ? (Action<Response>) null : r =>
      {
     if (r.Success)
     {
        var res = JsonConvert.DeserializeObject<LogResponse>(r.Raw);
        res.Success = true;
        callback(res);
     }
     else
     {
        var res = new LogResponse{ Success = false };
        callback(res);
     }
      };
      communicator.SendPayload(Communicator.POST, string.Concat("inputs/", _inputKey), message, json, callbackWrapper);
 }
Esempio n. 18
0
 public async Task <LogResponse> LoginAsync() => LogResponse.ParseFromUsereg(await PostAsync(LogUri, new Dictionary <string, string>
 {
     ["action"]          = "login",
     ["user_login_name"] = Username,
     ["user_password"]   = CryptographyHelper.GetMD5(Password)
 }));