All Projects → mattwcole → gelf-extensions-logging

mattwcole / gelf-extensions-logging

Licence: MIT License
GELF provider for Microsoft.Extensions.Logging

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to gelf-extensions-logging

logback-gelf-appender
Logback appender that sends GELF messages
Stars: ✭ 38 (-53.09%)
Mutual labels:  gelf, graylog
Graylog2 Server
Free and open source log management
Stars: ✭ 5,952 (+7248.15%)
Mutual labels:  gelf, graylog
logspout-gelf
Logspout with GELF adapter
Stars: ✭ 16 (-80.25%)
Mutual labels:  gelf, graylog
NLog.Targets.GraylogHttp
NLog target that pushes log messages to Graylog using the Http input.
Stars: ✭ 17 (-79.01%)
Mutual labels:  gelf, graylog
pem-utils
Managed .NET (C#) utility library for working with PEM files with DER/ASN.1 encoding
Stars: ✭ 62 (-23.46%)
Mutual labels:  dotnet-standard
chess
Chess (game)(♟) built in C# and ASCII art.
Stars: ✭ 20 (-75.31%)
Mutual labels:  dotnet-standard
graylog-zeek-content-pack
BRO/Zeek IDS content pack contains pipeline rules, a stream, a dashboard displaying interesting activity, and a syslog tcp input to capture and index BRO/Zeek logs coming from a remote sensor.
Stars: ✭ 18 (-77.78%)
Mutual labels:  graylog
King.Service
Task scheduling for .NET
Stars: ✭ 34 (-58.02%)
Mutual labels:  dotnet-standard
pastebin-csharp
API client for Pastebin in C#
Stars: ✭ 25 (-69.14%)
Mutual labels:  dotnet-standard
cv4pve-api-dotnet
Proxmox VE Client API .Net C#
Stars: ✭ 25 (-69.14%)
Mutual labels:  dotnet-standard
barcoder
Lightweight Barcode Encoding Library for .NET Framework, .NET Standard and .NET Core.
Stars: ✭ 76 (-6.17%)
Mutual labels:  dotnet-standard
WebDavClient
Asynchronous cross-platform WebDAV client for .NET Core
Stars: ✭ 98 (+20.99%)
Mutual labels:  dotnet-standard
oryx
.NET Cross platform and highly composable middleware for building web request handlers in F#
Stars: ✭ 178 (+119.75%)
Mutual labels:  dotnet-standard
dapr-sidekick-dotnet
Dapr Sidekick for .NET - a lightweight lifetime management component for Dapr
Stars: ✭ 113 (+39.51%)
Mutual labels:  dotnet-standard
cognite-sdk-dotnet
.NET SDK for Cognite Data Fusion (CDF)
Stars: ✭ 14 (-82.72%)
Mutual labels:  dotnet-standard
CommandLineParser.Core
💻 A simple, light-weight and strongly typed Command Line Parser made in .NET Standard!
Stars: ✭ 32 (-60.49%)
Mutual labels:  dotnet-standard
Mutatio
Visual Studio for Mac add-in/extension for converting old PCLs to .NET Standard 2.0 targeting projects automatically.
Stars: ✭ 27 (-66.67%)
Mutual labels:  dotnet-standard
Slugify
Simple Slug / Clean URL generator helper for Microsoft .NET framework / .NET Standard.
Stars: ✭ 53 (-34.57%)
Mutual labels:  dotnet-standard
HardwareInformation
.NET Standard Cross-Platform Hardware Information Gatherer
Stars: ✭ 37 (-54.32%)
Mutual labels:  dotnet-standard
Workday.WebServices
Workday API clients
Stars: ✭ 18 (-77.78%)
Mutual labels:  dotnet-standard

Gelf.Extensions.Logging travis downloads nuget license

GELF provider for Microsoft.Extensions.Logging for sending logs to Graylog, Logstash and more from .NET Standard 2.0+ compatible components.

Usage

Start by installing the NuGet package.

dotnet add package Gelf.Extensions.Logging

ASP.NET Core

Use the LoggingBuilder.AddGelf() extension method from the Gelf.Extensions.Logging namespace when configuring your host.

public static IHostBuilder CreateHostBuilder(string[] args) => Host
    .CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder
            .UseStartup<Startup>()
            .ConfigureLogging((context, builder) => builder.AddGelf(options =>
            {
                // Optional customisation applied on top of settings in Logging:GELF configuration section.
                options.LogSource = context.HostingEnvironment.ApplicationName;
                options.AdditionalFields["machine_name"] = Environment.MachineName;
                options.AdditionalFields["app_version"] = Assembly.GetEntryAssembly()
                    ?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
            }));
    });

Logger options are taken from the "GELF" provider section in appsettings.json in the same way as other providers. These are customised further in the code above.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    },
    "GELF": {
      "Host": "localhost",
      "Port": 12201,                 // Not required if using default 12201.
      "Protocol": "UDP",             // Not required if using default UDP.
      "LogSource": "My.App.Name",    // Not required if set in code as above.
      "AdditionalFields": {          // Optional fields added to all logs.
        "foo": "bar"
      },
      "LogLevel": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  }
}

For a full list of options e.g. UDP/HTTP(S) settings, see GelfLoggerOptions. See the samples directory full examples. For more information on providers and logging in general, see the aspnetcore logging documentation.

Auto Reloading Config

Settings can be changed at runtime and will be applied without the need for restarting your app. In the case of invalid config (e.g. missing hostname) the change will be ignored.

Additional Fields

By default, logger and exception fields are included on all messages (the exception field is only added when an exception is passed to the logger). There are a number of other ways to attach data to logs.

Global Fields

Global fields can be added to all logs by setting them in GelfLoggerOptions.AdditionalFields (machine_name, app_version and foo in the previous example).

Scoped Fields

Log scopes can also be used to attach fields to a group of related logs. Create a log scope with a ValueTuple<string, string>, ValueTuple<string, int/double/decimal> (or any other numeric value) or Dictionary<string, object> to do so. Note that any other types passed to BeginScope() will be ignored, including Dictionary<string, string>.

using (_logger.BeginScope(("correlation_id", correlationId)))
{
    // Field will be added to all logs within this scope (using any ILogger<T> instance).
}

using (_logger.BeginScope(new Dictionary<string, object>
{
    ["order_id"] = orderId,
    ["customer_id"] = customerId
}))
{
    // Fields will be added to all logs within this scope (using any ILogger<T> instance).
}

Structured/Semantic Logging

Semantic logging is also supported meaning fields can be extracted from individual log lines like so.

_logger.LogInformation("Order {order_id} took {order_time} seconds to process", orderId, orderTime);

Here the message will contain order_id and order_time fields.

Additional Fields Factory

It is possible to derive additional fields from log data with a factory function. This is useful for adding more information than what is provided by default e.g. the Microsoft log level or exception type.

options.AdditionalFieldsFactory = (logLevel, eventId, exception) =>
    new Dictionary<string, object>
    {
        ["log_level"] = logLevel.ToString(),
        ["exception_type"] = exception?.GetType().ToString()
    };

Log Filtering

The "GELF" provider can be filtered in the same way as the default providers (details here).

Compression

By default UDP messages of 512 bytes or more are GZipped however this behaviour can be disabled or altered with GelfLoggerOptions.CompressUdp and GelfLoggerOptions.UdpCompressionThreshold.

Logstash GELF Plugin

The Logstash GELF plugin requires entirely compressed UDP messages in which case the UDP compression threshold must be set to 0.

Testing

This repository contains a Docker Compose file that can be used for creating a local Graylog stack using the Graylog Docker image. This can be useful for testing application logs locally. Requires Docker and Docker Compose.

  • docker-compose up
  • Navigate to http://localhost:9000
  • Credentials: admin/admin
  • Create a UDP input on port 12201 and set GelfLoggerOptions.Host to localhost.

Contributing

Pull requests welcome! In order to run tests, first run docker-compose up to create the Graylog stack. Existing tests log messages and use the Graylog API to assert that they have been sent correctly. A UDP input will be created as part of the test setup (if not already present), so there is no need to create one manually. Build and tests are run on CI in Docker, meaning it is possible to run the build locally under identical conditions using docker-compose -f docker-compose.ci.build.yml -f docker-compose.yml up --abort-on-container-exit.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].