// ReSharper disable once MemberCanBePrivate.Global public new async System.Threading.Tasks.Task ProcessLogQueue() { #if DEBUG System.Console.WriteLine($"{{ \"{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName}.{System.Reflection.MethodBase.GetCurrentMethod().Name}\" : {{ "); #endif while (!this.CancellationTokenSource.IsCancellationRequested) { var limit = this.BatchSize ?? System.Int32.MaxValue; while (limit > 0 && this.MessageQueue.TryTake(out var message)) { this.CurrentBatch.Add(message); limit--; } var currentBatchCount = this.CurrentBatch.Count; #if DEBUG System.Console.WriteLine($"\"currentBatchCount\" : {currentBatchCount} , "); #endif if (currentBatchCount > 0) { #if DEBUG System.Console.WriteLine($"\"currentBatchCount\" : {currentBatchCount} , "); #endif try { await this.WriteMessagesAsync(this.CurrentBatch, this.CancellationTokenSource.Token); } catch (System.Exception excep) { // Write to the Azure App Services Data Collector fails, redirecting messages // to the base FileLogger var stateMsg = $"Error 000793 in \"{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName}.{System.Reflection.MethodBase.GetCurrentMethod().Name}\" sending current batch count of \"{currentBatchCount}messages to WriteMessagesAsync()"; var logMessage = new Generic.LogMessage <System.String>(Microsoft.Extensions.Logging.LogLevel.Error, Events.E00793, stateMsg, excep, this.AzureDataCollectorFormatter); this.AddMessage(logMessage); await base.WriteMessagesAsync(this.CurrentBatch, this.CancellationTokenSource.Token); #if DEBUG System.Console.WriteLine($"\"error\" : \"this.WriteMessagesAsync error in ProcessLogQueue\""); #endif } #if DEBUG finally { System.Console.WriteLine($"\"success\" : \"this.WriteMessagesAsync success in ProcessLogQueue\""); } #endif this.CurrentBatch.Clear(); } await this.IntervalAsync(this.Interval, this.CancellationTokenSource.Token); } }
/// <summary> /// Adds a message to the _messageQueue /// </summary> /// <param name="message"></param> protected internal void AddMessage <TState>(Generic.LogMessage <TState> message) { #if DEBUG System.Console.WriteLine($"{{ {System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName}.{System.Reflection.MethodBase.GetCurrentMethod().Name} }}"); #endif if (this.MessageQueue.IsAddingCompleted) { return; } try { this.MessageQueue.Add(message, this.CancellationTokenSource.Token); } catch { // TODO cancellation token canceled or CompleteAdding called } }
public System.String AzureDataCollectorFormatter <TState>( [JetBrains.Annotations.CanBeNull] System.Guid?correlationId, [JetBrains.Annotations.CanBeNull] Microsoft.Extensions.Logging.EventId?eventId, [JetBrains.Annotations.CanBeNull] System.Exception exception, [JetBrains.Annotations.CanBeNull] Microsoft.Extensions.Logging.LogLevel?logLevel, [JetBrains.Annotations.CanBeNull] System.String logType, [JetBrains.Annotations.NotNull] TState state, [JetBrains.Annotations.CanBeNull] System.DateTimeOffset?timestamp ) { var m = new Generic.LogMessage <TState> { CorrelationId = correlationId ?? System.Guid.NewGuid(), EventId = eventId, Exception = exception, Formatter = this.AzureDataCollectorFormatter, LogLevel = logLevel ?? ((exception == null) ? Microsoft.Extensions.Logging.LogLevel.Information : Microsoft.Extensions.Logging.LogLevel.Error), LogType = logType ?? typeof(TState).FullName.RemoveAllSpecialCharacters(), State = state, Timestamp = timestamp ?? System.DateTimeOffset.Now }; return(m.ToJson()); }
/// <summary> /// Send a request to the POST API endpoint /// </summary> /// <param name="logType"></param> /// <param name="message"></param> /// <param name="customerId"></param> /// <param name="sharedKey"></param> // ReSharper disable once MemberCanBePrivate.Global private async System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> PostData(System.String logType, System.String message, System.String customerId, System.String sharedKey) { var url = $"https://{customerId}.ods.opinsights.azure.com/api/logs?api-version=2016-04-01"; #if DEBUG System.Console.WriteLine($"{{ {System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName}.{System.Reflection.MethodBase.GetCurrentMethod().Name} : {{"); System.Console.WriteLine($"\"customerId\" : \"{customerId}\","); System.Console.WriteLine($"\"logType\" : \"{logType}\","); System.Console.WriteLine($"\"sharedKeySecret\" : \"{sharedKey}\","); System.Console.WriteLine($"\"message\" : {{ {message} }}, "); System.Console.WriteLine($"\"url\" : \"{url}\" , "); #endif var response = new System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage>(() => null); // Note the formatting of the datestring vs timestamp var datestring = System.DateTime.UtcNow.ToString("r"); var authorization = this.GetAuthorizationHash(message, datestring, customerId, sharedKey); var client = new System.Net.Http.HttpClient { Timeout = this.WebTimeOut }; try { client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Log-Type", logType); client.DefaultRequestHeaders.Add("Authorization", authorization); client.DefaultRequestHeaders.Add("x-ms-date", datestring); // let the Log Analytics HTTP DataCollector API assign the Timestamp //System.Console.WriteLine(Program.TimeStampField); //client.DefaultRequestHeaders.Add("time-generated-field", Program.TimeStampField); System.Net.Http.HttpContent httpContent = new System.Net.Http.StringContent(message, System.Text.Encoding.UTF8); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); response = client.PostAsync(new System.Uri(url), httpContent); #if DEBUG System.Console.WriteLine($"\"PostDate response\": {{ {response.ToJson()} }}"); #endif } catch (System.Exception excep) { var stateMsg = $"Error E00696 in \"{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName}.{System.Reflection.MethodBase.GetCurrentMethod().Name}\" sending \"{message.ToJson()}\" to \"{url}\""; // ReSharper disable once UnusedVariable var ex = new System.Exception(stateMsg, excep); var logMessage = new Generic.LogMessage <System.String>(Microsoft.Extensions.Logging.LogLevel.Error, Events.E00696, stateMsg, excep, this.AzureDataCollectorFormatter); this.AddMessage(logMessage); #if DEBUG System.Console.WriteLine($"\"PostDate Exception\": {{ {excep.ToJson()} }}"); #endif } #if DEBUG finally { System.Console.WriteLine($"}}"); } #endif return(await response); }