This commit is contained in:
Jeroen
2023-10-18 15:12:50 +02:00
parent 98b67e6e9b
commit a0d98a62b0
3 changed files with 82 additions and 19 deletions

View File

@@ -7,8 +7,10 @@ using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using EonaCat.Json;
using EonaCat.Json.Linq;
using EonaCat.Logger.Extensions;
using EonaCat.Logger.GrayLog;
using EonaCat.Logger.Splunk.Models;
using EonaCat.Logger.Syslog;
using Microsoft.Extensions.Logging;
@@ -136,9 +138,9 @@ namespace EonaCat.Logger.Managers
logger.Log(logLevel, message);
}
public static async Task SendToSplunkServersAsync(LoggerSettings settings, string jsonPayload, bool sendToSplunkServer)
public static async Task SendToSplunkServersAsync(LoggerSettings settings, SplunkPayload splunkPayload, bool sendToSplunkServer)
{
if (settings == null || !sendToSplunkServer || string.IsNullOrWhiteSpace(jsonPayload))
if (settings == null || !sendToSplunkServer || splunkPayload == null)
return;
if (settings.SplunkServers == null)
@@ -165,17 +167,11 @@ namespace EonaCat.Logger.Managers
{
try
{
using (var httpClient = new HttpClient(splunkServer.SplunkClientHandler))
var response = await splunkServer.SendAsync(splunkPayload);
if (!response.IsSuccessStatusCode)
{
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Add("Authorization", $"Splunk {splunkServer.SplunkHecToken}");
var response = await httpClient.PostAsync(splunkServer.SplunkHecUrl, content);
if (!response.IsSuccessStatusCode)
{
OnException?.Invoke(null, new ErrorMessage { Message = $"Failed to send log to Splunk '{splunkServer.SplunkHecUrl}'. Status code: {response.StatusCode}" });
}
OnException?.Invoke(null, new ErrorMessage { Message = $"Failed to send log to Splunk '{splunkServer.SplunkHecUrl}'. Status code: {response.StatusCode}" });
}
}
catch (Exception exception)
@@ -191,12 +187,14 @@ namespace EonaCat.Logger.Managers
if (settings == null || !sendToSplunkServer || string.IsNullOrWhiteSpace(message))
return;
var jsonPayload = JsonHelper.ToJson(new
var splunkPayload = new SplunkPayload
{
@event = message,
sourcetype = logType
});
await SendToSplunkServersAsync(settings, jsonPayload, sendToSplunkServer);
Host = Environment.MachineName,
EventData = message,
SourceType = logType
};
await SendToSplunkServersAsync(settings, splunkPayload, sendToSplunkServer);
}
internal static async Task SendToGrayLogServersAsync(LoggerSettings settings, string message, ELogType logLevel, string facility, string source, bool sendToGrayLogServer, string version = "1.1")