Add centralized log collection to ASP.NET Core apps with one line of code.
Clone or download

README.md

Seq.Extensions.Logging Build status NuGet Pre Release Join the chat at https://gitter.im/datalust/seq

Seq is a flexible self-hosted back-end for the ASP.NET Core logging subsystem (Microsoft.Extensions.Logging). Log events generated by the framework and application code are sent over HTTP to a Seq server, where the structured data associated with each event is used for powerful filtering, correlation, and analysis.

For an example, see the dotnetconf deep dive session.

Screenshot

This package makes it a one-liner to configure ASP.NET Core logging with Seq.

Getting started

The instructions that follow are for .NET Core 2.0+.

Add the NuGet package to your project either by editing the CSPROJ file, or using the NuGet package manager:

Install-Package Seq.Extensions.Logging

In Program.cs, call AddSeq() on the provided ILoggingBuilder.

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));

            // Add this line
            logging.AddSeq("http://localhost:5341");

            logging.AddConsole();
            logging.AddDebug();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

The framework will inject ILogger instances into controllers and other classes:

class HomeController : Controller
{
    readonly ILogger<HomeController> _log;
    
    public HomeController(ILogger<HomeController> log)
    {
        _log = log;
    }
    
    public IActionResult Index()
    {
        _log.LogInformation("Hello, world!");
    }
}

Log messages will be sent to Seq in batches and be visible in the Seq user interface. Observe that correlation identifiers added by the framework, like RequestId, are all exposed and fully-searchable in Seq.

Logging with message templates

Seq supports the templated log messages used by Microsoft.Extensions.Logging. By writing events with named format placeholders, the data attached to the event preserves the individual property values.

var fizz = 3, buzz = 5;
log.LogInformation("The current values are {Fizz} and {Buzz}", fizz, buzz);

This records an event like:

Property Value
Message "The current values are 3 and 5"
Fizz 3
Buzz 5

Seq makes these properties searchable without additional log parsing. For example, a filter expression like Fizz < 4 would match the event above.

Additional configuration

The AddSeq() method exposes some basic options for controlling the connection and log volume.

Parameter Description Example value
apiKey A Seq API key to authenticate or tag messages from the logger "1234567890"
levelOverrides A dictionary mapping logger name prefixes to minimum logging levels new Dictionary<string,LogLevel>{ ["Microsoft"] = LogLevel.Warning }
minimumLevel The level below which events will be suppressed (the default is Information) LogLevel.Trace

JSON configuration

The logging level, Seq server URL, API key and other settings can be read from JSON configuration if desired.

In appsettings.json add a "Seq" property to "Logging" to configure levels for the Seq provider:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information"
    },
    "Seq": {
      "LogLevel": {
        "Default": "Trace",
        "System": "Information",
        "Microsoft": "Warning"
      }
    }
  },
  "Seq": {
    "ServerUrl": "http://localhost:5341",
    "ApiKey": "1234567890",
  }
}

An additional root "Seq" property is used to configure the server URL and API key. To use this, pass the configuration section to the AddSeq() method:

        logging.AddSeq(Configuration.GetSection("Seq"));

Dynamic log level control

The logging provider will dynamically adjust the default logging level up or down based on the level associated with an API key in Seq. For further information see the Seq documentation.

Troubleshooting

Nothing showed up, what can I do?

If events don't appear in Seq after pressing the refresh button in the filter bar, either your application was unable to contact the Seq server, or else the Seq server rejected the log events for some reason.

Server-side issues

The Seq server may reject incoming events if they're missing a required API key, if the payload is corrupted somehow, or if the log events are too large to accept.

Server-side issues are diagnosed using the Seq Ingestion Log, which shows the details of any problems detected on the server side. The ingestion log is linked from the Settings > Diagnostics page in the Seq user interface.

Client-side issues

If there's no information in the ingestion log, the application was probably unable to reach the server because of network configuration or connectivity issues. These are reported to the application through SelfLog.

Add the following line after the logger is configured to print any error information to the console:

Seq.Extensions.Logging.SelfLog.Enable(Console.Error);

If the console is not available, you can pass a delegate into SelfLog.Enable() that will be called with each error message:

Seq.Extensions.Logging.SelfLog.Enable(message => {
    // Do something with `message`
});

Troubleshooting checklist

  • Check the Seq Ingestion Log, as described in the Server-side issues section above.
  • Turn on the SelfLog as described above to check for connectivity problems and other issues on the client side.
  • Raise an issue, ask for help on the Seq support forum or email support@getseq.net.

Migrating to Serilog

This package is based on a subset of the powerful Serilog library. Not all of the options supported by the Serilog and Seq client libraries are present in the Seq.Extensions.Logging package. Migrating to the full Serilog API however is very easy:

  1. Install packages Serilog, Serilog.Extensions.Logging and Serilog.Sinks.Seq.
  2. Follow the instructions here to change AddSeq() into AddSerilog() with a LoggerConfiguration object passed in
  3. Add WriteTo.Seq() to the Serilog configuration as per the example given for the Seq sink for Serilog