Git Product home page Git Product logo

serilog-sinks-loki's Introduction

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!

serilog-sinks-loki's People

Contributors

josephwoodward avatar falco20019 avatar anderssonpeter avatar michaelosthege avatar jincod avatar senritsu avatar aragas avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.