Created
November 22, 2018 20:19
-
-
Save rasmuskl/b280b6fe4c6942ad6ec29244666cfc07 to your computer and use it in GitHub Desktop.
A Humio Sink for Serilog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Newtonsoft.Json; | |
using Serilog; | |
using Serilog.Events; | |
using Serilog.Sinks.PeriodicBatching; | |
namespace SerilogHumioConsole | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Log.Logger = new LoggerConfiguration() | |
.MinimumLevel.Debug() | |
.WriteTo.Sink(new HumioSink("sandbox", "ingest token :)")) | |
.CreateLogger(); | |
Log.Information("Test x=42"); | |
Log.Information("Test x=45"); | |
Log.Information("Test x=50"); | |
Log.Information("Test x=55"); | |
Log.Information("Test x=12"); | |
Console.ReadKey(); | |
} | |
} | |
public class HumioSink : PeriodicBatchingSink | |
{ | |
private readonly string _ingestToken; | |
private readonly IFormatProvider _formatProvider; | |
private static readonly HttpClient HttpClient = new HttpClient(); | |
private readonly Uri _uri; | |
public HumioSink(string dataspace, string ingestToken, IFormatProvider formatProvider = null) : base(10, TimeSpan.FromSeconds(5)) | |
{ | |
_ingestToken = ingestToken; | |
_formatProvider = formatProvider; | |
_uri = new Uri($"https://go.humio.com/api/v1/dataspaces/{dataspace}/ingest-messages"); | |
} | |
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events) | |
{ | |
try | |
{ | |
var messages = events.Select(e => $"{e.Timestamp:o} - {e.RenderMessage(_formatProvider)}").ToArray(); | |
var payload = new[] { new { type = "kv", messages } }; | |
var jsonContent = JsonConvert.SerializeObject(payload); | |
var request = new HttpRequestMessage(HttpMethod.Post, _uri) { Content = new StringContent(jsonContent, Encoding.UTF8, "application/json") }; | |
request.Headers.Add("Authorization", $"Bearer {_ingestToken}"); | |
var response = await HttpClient.SendAsync(request); | |
if (response.StatusCode != HttpStatusCode.OK) | |
{ | |
Console.WriteLine($"Failed to ship logs to Humio: {response.StatusCode} - {response.ReasonPhrase} - {await response.Content.ReadAsStringAsync()}"); | |
} | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine($"Failed to ship logs to Humio: {e}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment