Exemplo n.º 1
0
        private void HttpRequest(string log)
        {
            bool isSendALAHeaderErr = false;
            bool isSendALADataErr   = false;

            while (true)
            {
                try
                {
                    if (ConfigSettings.ALAEnableDebugConsoleLog)
                    {
                        if (isSendALAHeaderErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics header...");
                        }

                        if (isSendALADataErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics data...");
                        }
                    }

                    headerBuilder.Clear();

                    string result = string.Empty;

                    var    utf8Encoding = new UTF8Encoding();
                    Byte[] content      = utf8Encoding.GetBytes(log);

                    var rfcDate   = DateTime.Now.ToUniversalTime().ToString("r");
                    var signature = HashSignature("POST", content.Length, "application/json", rfcDate, "/api/logs");

                    string alaServerAddr    = $"{appender.WorkspaceId}.ods.opinsights.azure.com";
                    string alaServerContext = $"/api/logs?api-version={appender.AzureApiVersion}";

                    // Send request headers
                    headerBuilder.AppendLine($"POST {alaServerContext} HTTP/1.1");
                    headerBuilder.AppendLine($"Host: {alaServerAddr}");
                    headerBuilder.AppendLine($"Content-Length: " + content.Length);   // only for POST request
                    headerBuilder.AppendLine("Content-Type: application/json");
                    headerBuilder.AppendLine($"Log-Type: {appender.LogType}");
                    headerBuilder.AppendLine($"x-ms-date: {rfcDate}");
                    headerBuilder.AppendLine($"Authorization: {signature}");
                    headerBuilder.AppendLine($"time-generated-field: {appender.coreFields.DateFieldName}");
                    headerBuilder.AppendLine("Connection: close");
                    headerBuilder.AppendLine();
                    var header = Encoding.ASCII.GetBytes(headerBuilder.ToString());

                    // Send http headers
                    string headerRes = alaClient.Write(header, 0, header.Length, true);
                    if (!headerRes.Equals("isHeader"))
                    {
                        isSendALAHeaderErr = true;
                        string errMessage = $"send Azure Log Analytics header failed - {headerRes}";
                        if (ConfigSettings.ALAEnableDebugConsoleLog)
                        {
                            appender.log.Err($"[{appender.Name}] - {errMessage}");
                        }
                        throw new Exception(errMessage);
                    }

                    // Send payload data
                    string httpResultBody = alaClient.Write(content, 0, content.Length);


                    if (!string.IsNullOrWhiteSpace(httpResultBody))
                    {
                        isSendALADataErr = true;
                        string errMessage = $"send Azure Log Analytics data failed - {httpResultBody}";
                        if (ConfigSettings.ALAEnableDebugConsoleLog)
                        {
                            appender.log.Err($"[{appender.Name}] - {errMessage}");
                        }
                        throw new Exception(errMessage);
                    }
                    try
                    {
                        //no loggings in case of LogManager.Shutdown() -> AbortWorker;
                        appender.log.Inf($"[{appender.Name}] - {log}", appender.LogMessageToFile);
                    }
                    catch
                    {
                        //continue
                    }

                    if (ConfigSettings.ALAEnableDebugConsoleLog)
                    {
                        if (isSendALAHeaderErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics header succeeded");
                        }

                        if (isSendALADataErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics data succeeded");
                        }
                    }

                    isSendALAHeaderErr = false;
                    isSendALADataErr   = false;
                }
                catch (Exception ex)
                {
                    // Reopen the lost connection.
                    string errMessage = $"reopen lost connection and retry...";
                    if (ConfigSettings.ALAEnableDebugConsoleLog)
                    {
                        appender.log.Err($"[{appender.Name}] - {errMessage}");
                        System.Console.WriteLine($@"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")}|Log4ALA|[{appender.Name}]|ERROR|[{nameof(QueueLogger)}.HttpRequest] - [{errMessage}]");
                    }
                    Connect();
                    continue;
                }

                //unblock AbortWorker if AbortWorker has canceld the background worker thread
                if (this.cToken.IsCancellationRequested == true)
                {
                    this.manualResetEvent.Set();
                }

                break;
            }
        }
Exemplo n.º 2
0
        private void HttpRequest(string log)
        {
            bool isSendALAHeaderErr = false;
            bool isSendALADataErr   = false;

            while (true)
            {
                try
                {
                    if (ConfigSettings.ALAEnableDebugConsoleLog)
                    {
                        if (isSendALAHeaderErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics header...");
                        }

                        if (isSendALADataErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics data...");
                        }
                    }

                    headerBuilder.Clear();

                    string result = string.Empty;

                    var    utf8Encoding = new UTF8Encoding();
                    Byte[] content      = utf8Encoding.GetBytes(log);

                    var rfcDate   = DateTime.Now.ToUniversalTime().ToString("r");
                    var signature = HashSignature("POST", content.Length, "application/json", rfcDate, "/api/logs");

                    // for http debugging please install httpbin (https://github.com/requests/httpbin) locally as docker container:
                    //
                    //      docker pull kennethreitz/httpbin
                    //
                    // and start with:
                    //
                    //      docker run -p 80:80 kennethreitz / httpbin
                    //
                    // and replacefor alaServerAddr with http://localhost/anything by setting the property debugHTTPReqURI=http://localhost/anything to inspect the http request
                    // which will then be logged into log4ALA_info.log instead of sending to Azure Log Analytics data collector API.

                    string alaServerAddr    = $"{appender.WorkspaceId}.ods.opinsights.azure.com";
                    string alaServerContext = $"/api/logs?api-version={appender.AzureApiVersion}";

                    if (!string.IsNullOrWhiteSpace(appender.DebugHTTPReqURI))
                    {
                        string[] uriSplit = appender.DebugHTTPReqURI.Split('/');
                        alaServerAddr    = uriSplit[2];
                        alaServerContext = $"/{uriSplit[3]}{alaServerContext}";
                    }


                    // Send request headers
                    headerBuilder.AppendLine($"POST {alaServerContext} HTTP/1.1");
                    headerBuilder.AppendLine($"Host: {alaServerAddr}");
                    headerBuilder.AppendLine($"Content-Length: " + content.Length);   // only for POST request
                    headerBuilder.AppendLine("Content-Type: application/json");
                    headerBuilder.AppendLine($"Log-Type: {appender.LogType}");
                    headerBuilder.AppendLine($"x-ms-date: {rfcDate}");
                    headerBuilder.AppendLine($"Authorization: {signature}");
                    headerBuilder.AppendLine($"time-generated-field: {appender.coreFields.DateFieldName}");
                    headerBuilder.AppendLine("Connection: close");
                    headerBuilder.AppendLine();
                    var header = utf8Encoding.GetBytes(headerBuilder.ToString());


                    string httpResultBody;
                    if (!string.IsNullOrWhiteSpace(appender.DebugHTTPReqURI))
                    {
                        headerBuilder.Append(log);
                        string        reqStr          = headerBuilder.ToString();
                        var           req             = utf8Encoding.GetBytes(reqStr);
                        StringBuilder responseBuilder = new StringBuilder();


                        using (Stream networkStream = alaClient.ActiveStream)
                        {
                            networkStream.Write(req, 0, req.Length);
                            networkStream.Flush();


                            #if NET45 || NET451
                            Task.Run(() =>
                            #else
                            Task.Factory.StartNew(() =>
                            #endif
                            {
                                var bufout  = new byte[req.Length];
                                int readlen = 0;
                                do
                                {
                                    readlen = networkStream.Read(bufout, 0, bufout.Length);
                                    responseBuilder.Append(System.Text.Encoding.UTF8.GetString(bufout, 0, readlen));
                                } while (readlen != 0);
                            }).Wait();
                        }
                        httpResultBody = responseBuilder.ToString();
                    }
                    else
                    {
                        // Send http headers
                        string headerRes = alaClient.Write(header, 0, header.Length, true);

                        if (!headerRes.Equals("isHeader"))
                        {
                            isSendALAHeaderErr = true;
                            string errMessage  = $"send Azure Log Analytics header failed - {headerRes}";
                            if (ConfigSettings.ALAEnableDebugConsoleLog)
                            {
                                appender.log.Err($"[{appender.Name}] - {errMessage}");
                            }
                            throw new Exception(errMessage);
                        }

                        // Send payload data
                        httpResultBody = alaClient.Write(content, 0, content.Length);
                    }


                    if (!string.IsNullOrWhiteSpace(httpResultBody))
                    {
                        if (string.IsNullOrWhiteSpace(appender.DebugHTTPReqURI))
                        {
                            isSendALADataErr  = true;
                            string errMessage = $"send Azure Log Analytics data failed - {httpResultBody}";
                            if (ConfigSettings.ALAEnableDebugConsoleLog)
                            {
                                appender.log.Err($"[{appender.Name}] - {errMessage}");
                            }
                            throw new Exception(errMessage);
                        }
                        else
                        {
                            //appender.log.Inf($"[{appender.Name}] - http request: \n{headerBuilder.ToString()}{log}", appender.LogMessageToFile);
                            appender.log.Inf($"[{appender.Name}] - http debug response from [{appender.DebugHTTPReqURI}]: \n{httpResultBody}", appender.LogMessageToFile);
                        }
                    }
                    try
                    {
                        if (string.IsNullOrWhiteSpace(appender.DebugHTTPReqURI))
                        {
                            //no loggings in case of LogManager.Shutdown() -> AbortWorker;
                            appender.log.Inf($"[{appender.Name}] - {log}", appender.LogMessageToFile);
                        }
                    }
                    catch
                    {
                        //continue
                    }

                    if (ConfigSettings.ALAEnableDebugConsoleLog)
                    {
                        if (isSendALAHeaderErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics header succeeded");
                        }

                        if (isSendALADataErr)
                        {
                            appender.log.Err($"[{appender.Name}] - retry sending Azure Log Analytics data succeeded");
                        }
                    }

                    isSendALAHeaderErr = false;
                    isSendALADataErr = false;
                }
                catch (Exception ex)
                {
                    // Reopen the lost connection.
                    string errMessage = $"reopen lost connection and retry...";
                    if (ConfigSettings.ALAEnableDebugConsoleLog)
                    {
                        appender.log.Err($"[{appender.Name}] - {errMessage}");
                        System.Console.WriteLine($@"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")}|Log4ALA|[{appender.Name}]|ERROR|[{nameof(QueueLogger)}.HttpRequest] - [{errMessage}]");
                    }
                    Connect();
                    continue;
                }

                //unblock AbortWorker if AbortWorker has canceld the background worker thread
                if (this.cToken.IsCancellationRequested == true)
                {
                    this.manualResetEvent.Set();
                }

                break;
            }
        }