• Stars
    star
    126
  • Rank 283,270 (Top 6 %)
  • Language
    C#
  • License
    MIT License
  • Created over 5 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Serilog Sink for Loki, Grafana's new Prometheus inspired log aggregator

Serilog.Sinks.Loki

.NET Core

This is a Serilog Sink for Grafana's new Loki Log Aggregator.

What is Loki?

Loki is a horizontally-scalable, highly-available, multi-tenant log aggregation system inspired by Prometheus. It is designed to be very cost effective and easy to operate, as it does not index the contents of the logs, but rather a set of labels for each log stream.

You can find more information about what Loki is over on Grafana's website here.

Loki Screenshot

Current Features:

  • Formats and batches log entries to Loki via HTTP
  • Ability to provide global Loki log labels
  • Comes baked with an HTTP client, but your own can be provided
  • Provides contextual log labels

Coming soon:

  • Write logs to disk in the correct format to send via Promtail
  • Send logs to Loki via HTTP using Snappy compression

Installation

The Serilog.Sinks.Loki NuGet package can be found here. Alternatively you can install it via one of the following commands below:

NuGet command:

Install-Package Serilog.Sinks.Loki

.NET Core CLI:

dotnet add package Serilog.Sinks.Loki

Basic Example:

// var credentials = new BasicAuthCredentials("http://localhost:3100", "<username>", "<password>");
var credentials = new NoAuthCredentials("http://localhost:3100"); // Address to local or remote Loki server

Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .Enrich.FromLogContext()
        .WriteTo.LokiHttp(credentials)
        .CreateLogger();

var exception = new {Message = ex.Message, StackTrace = ex.StackTrace};
Log.Error(exception);

var position = new { Latitude = 25, Longitude = 134 };
var elapsedMs = 34;
Log.Information("Message processed {@Position} in {Elapsed:000} ms.", position, elapsedMs);

Log.CloseAndFlush();

Adding global labels

Loki indexes and groups log streams using labels, in Serilog.Sinks.Loki you can attach labels to all log entries by passing an implementation ILogLabelProvider to the WriteTo.LokiHttp(..) configuration method. This is ideal for labels such as instance IDs, environments and application names.

See Serilog.Sinks.Loki.Example/LogLabelProvider.cs for a basic LogLabelProvider implementation.

var credentials = new BasicAuthCredentials("http://localhost:3100", "<username>", "<password>");
var log = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .Enrich.FromLogContext()
        .WriteTo.LokiHttp(credentials, new LogLabelProvider())
        .CreateLogger();

Local, contextual labels

In some occasions you'll want to add context to your log stream within a particular class or method, this can be achieved using contextual labels:

using (LogContext.PushProperty("A", 1))
{
    log.Warning("Warning with Property A");
    log.Fatal("Fatal with Property A");
}

Custom HTTP Client

Serilog.Loki.Sink is built on top of the popular Serilog.Sinks.Http library to post log entries to Loki. With this in mind you can you can extend the default HttpClient (LokiHttpClient), or replace it entirely by implementing IHttpClient.

// ExampleHttpClient.cs

public class ExampleHttpClient : LokiHttpClient
{
    public override Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
    {
        return base.PostAsync(requestUri, content);
    }
}
// Usage

var credentials = new BasicAuthCredentials("http://localhost:3100", "<username>", "<password>");
var log = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .Enrich.FromLogContext()
        .WriteTo.LokiHttp(credentials, new LogLabelProvider(), new ExampleHttpClient())
        .CreateLogger();

Configure using appsettings.json

Serilog-Sinks-Loki can be configured with appsettings.json using Serilog.Settings.Configuration.
It support the following arguments serverUrl, username, password, credentials, labelProvider, httpClient, outputTemplate and formatProvider.
Not all fields can be used in combination look in LokiSinkExtensions.cs for the supported combinations.
credentials, labelProvider, httpClient, and formatProvider are classes and must be specified using the Namespace.ClassName, Assembly syntax.

"Serilog": {
  "Using": [ "Serilog.Sinks.Loki" ],
  "MinimumLevel": {
    "Default": "Verbose"
  },
  "Enrich": [ "FromLogContext" ],
  "WriteTo": [      
    {
      "Name": "LokiHttp",
      "Args": {
        "serverUrl": "https://loki:3000",
        "labelProvider": "Namespace.ClassName, Assembly"
      }
    }
  ]
}

Missing a feature or want to contribute?

This package is still in its infancy so if there's anything missing then please feel free to raise a feature request, either that or pull requests are most welcome!

More Repositories

1

GlobalExceptionHandlerDotNet

Exception handling as a convention in the ASP.NET Core request pipeline
C#
267
star
2

graphiql-dotnet

GraphiQL middleware for ASP.NET Core
CSS
142
star
3

VSCodeILViewer

A Visual Studio Code C# IL (Intermediate Language) Viewer
C#
93
star
4

Angular2PianoNoteTrainingGame

Angular 2 based piano note training game
TypeScript
83
star
5

DotNetInstallSdkGlobalTool

Global tool to make installing .NET version that little bit easier
C#
16
star
6

gin-errorhandling

Go
10
star
7

SlugityDotNet

Simple class library to sanitize text and turn it into a search engine friendly URL
C#
9
star
8

RouteUrlRedirector

ASP.NET Core MVC Middleware for redirecting old paths to new paths using either 301 or 302 redirects
C#
9
star
9

CKFinderJcrop

CKFinder plugin of a much needed image cropping feature using the JQuery based JCrop
JavaScript
5
star
10

tftp-server

A TFTP Server written in Go
Go
4
star
11

httpclient-interception-go

Go
3
star
12

chaosproxy

A simple means of introducing chaos into your infrastructure for Windows, Mac and Linux.
Go
2
star
13

git-hotspot

Go
2
star
14

TrafficCop

Simple rules based traffic manager for ASP.NET MVC
C#
2
star
15

SeleniumGridDotNetCore

C#
1
star
16

OpenApiApprovalTesting

C#
1
star
17

otelnats

1
star
18

NServiceBusPlayground

Heard lots of interesting things about NServiceBus so want to have a play
C#
1
star
19

BlazorDemo

C#
1
star
20

RazorPlayground

C#
1
star
21

WorldsSmallestViolin

Lunchtime Android project perfect for winding friends up.
Java
1
star
22

ExceptionRerouter

A simple exception rerouting library for ASP.NET MVC.
C#
1
star
23

AzureAdTemp

C#
1
star
24

HttpLogger

Go
1
star
25

NetworkProgrammingInGo

Go
1
star
26

TypeScriptSpaceShooter

A really simple Javascript based game I've been working on during lunchtime using TypeScript.
JavaScript
1
star