Method AddSerilog
- Namespace
- Ploch.CommandLine.Spectre.Serilog
- Assembly
- Ploch.CommandLine.Spectre.Serilog.dll
AddSerilog(IServiceCollection, IConfiguration?, string?, string?, string?, CultureInfo?)
Adds Serilog to the service collection with a comprehensive predefined configuration optimised for command-line applications.
public static IServiceCollection AddSerilog(this IServiceCollection services, IConfiguration? configuration = null, string? logName = null, string? logPath = null, string? template = null, CultureInfo? culture = null)
Parameters
servicesIServiceCollectionThe service collection to configure. Serilog will be registered as the primary logging provider, replacing any existing logging configuration.
configurationIConfigurationOptional configuration instance to read Serilog settings from. If provided, settings from the "Serilog" section will be used to customise the logging behaviour. The configuration will be applied after the predefined setup, allowing for overrides.
logNamestringOptional name for the log files. If not provided, the current process name will be used. This affects both the main log file and the error-specific log file names.
logPathstringOptional directory path where log files will be stored. If not provided, the application's base directory will be used. Both main and error log files will be created in this directory.
templatestringAn optional Serilog output template applied to the rolling log file.
cultureCultureInfoOptional culture used to format values in both log files (the main log and the error log). When null, the files are written with InvariantCulture, so their contents do not depend on the locale of the machine. Pass CurrentCulture for locale-formatted values. Console output is not affected.
Returns
- IServiceCollection
The same IServiceCollection instance to enable method chaining for additional service registrations.
Examples
// Basic setup with default configuration
services.AddSerilog();
// With configuration and custom log settings
services.AddSerilog(
configuration: configuration,
logName: "MyCommandLineApp",
logPath: @"C:\Logs"
);
// Method chaining with other services:
services.AddSerilog(configuration)
.AddScoped<IMyService, MyService>()
.AddSingleton<IAnotherService, AnotherService>();
Remarks
This method registers a SerilogConfigurationBundle with the service collection, and nothing else. It previously also configured Serilog a second time through the Microsoft.Extensions.Logging integration, which silently dropped the output template; that call was removed so the bundle is the single place the logger is configured.
The bundle configures three sinks (a rolling log file, a separate file for warnings and above — warnings, errors and fatal events — and the Spectre.Console console sink), enrichers (thread information, context), and formatting options suited to command-line applications. File logging includes automatic rotation.
Exceptions
- ArgumentNullException
Thrown when
servicesisnull.