diff --git a/docs/core/extensions/console-log-formatter.md b/docs/core/extensions/console-log-formatter.md new file mode 100644 index 0000000000000..bed1aa4804a5f --- /dev/null +++ b/docs/core/extensions/console-log-formatter.md @@ -0,0 +1,154 @@ +--- +title: Console log formatting +description: Learn how to use available console log formatting, or implement custom log formatting for your .NET applications. +author: IEvangelist +ms.author: dapine +ms.date: 10/22/2020 +--- + +# Console log formatting + +In .NET 5, support for custom formatting was added to console logs in the `Microsoft.Extensions.Logging.Console` namespace. There are three predefined formatting options available: [`Simple`](#simple), [`Systemd`](#systemd), and [`Json`](#json). + +> [!IMPORTANT] +> Previously, the enum allowed for selecting the desired log format, either human readable which was the `Default`, or single line which is also known as `Systemd`. However, these were **not** customizable, and are now deprecated. + +In this article, you will learn about console log formatters. The sample source code demonstrates how to: + +- Register a new formatter +- Select a registered formatter to use + - Either through code, or [configuration](configuration.md) +- Implement a custom formatter + - Update configuration via + - Enable custom color formatting + +## Register formatter + +The [`Console` logging provider](logging-providers.md#console) has several predefined formatters, and exposes the ability to author your own custom formatter. To register any of the available formatters, use the corresponding `Add{Type}Console` extension method: + +| Available types | Method to register type | +|--|--| +| | | +| | | +| | | + +### Simple + +To use the `Simple` console formatter, register it with `AddSimpleConsole`: + +:::code language="csharp" source="snippets/logging/console-formatter-simple/Program.cs" highlight="11-16"::: + +In the preceding sample source code, the formatter was registered. It provides logs with the ability to not only wrap information such as time and log level in each log message, but also allows for ANSI color embedding and indentation of messages. + +### Systemd + +The console logger: + +- Uses the "Syslog" log level format and severities +- Does **not** format messages with colors +- Always logs messages in a single line + +This is commonly useful for containers, which often make use of `Systemd` console logging. With .NET 5, the `Simple` console logger also enables a compact version that logs in a single line, and also allows for disabling colors as shown in an earlier sample. + +:::code language="csharp" source="snippets/logging/console-formatter-systemd/Program.cs" highlight="11-15"::: + +### Json + +To write logs in a JSON format, the `Json` console formatter is used. The sample source code shows how an ASP.NET Core app might register it. Using the `webapp` template, create a new ASP.NET Core app with the [dotnet new](../tools/dotnet-new.md) command: + +```dotnetcli +dotnet new webapp -o Console.ExampleFormatters.Json +``` + +When running the app, using the template code, you get the default log format below: + +``` +info: Microsoft.Hosting.Lifetime[0] + Now listening on: https://localhost:5001 +``` + +By default, the `Simple` console log formatter is selected with default configuration. You change this by calling `AddJsonConsole` in the *Program.cs*: + +:::code language="csharp" source="snippets/logging/console-formatter-json/Program.cs" highlight="17-26"::: + +Run the app again, with the above change, the log message is now formatted as JSON: + +:::code language="json" source="snippets/logging/console-formatter-json/example-output.json"::: + +> [!TIP] +> The `Json` console formatter, by default, logs each message in a single line. In order to make it more readable while configuring the formatter, set to `true`. + +## Set formatter with configuration + +The previous samples have shown how to register a formatter programmatically. Alternatively, this can be done with [configuration](configuration.md). Consider the previous web application sample source code, if you update the *appsettings.json* file rather than calling `ConfigureLogging` in the *Program.cs* file, you could get the same outcome. The updated `appsettings.json` file would configure the formatter as follows: + +:::code language="json" source="snippets/logging/console-formatter-json/appsettings.json" highlight="14-23"::: + +The two key values that need to be set are `"FormatterName"` and `"FormatterOptions"`. If a formatter with the value set for `"FormatterName"` is already registered, that formatter is selected, and its properties can be configured as long as they are provided as a key inside the `"FormatterOptions"` node. The predefined formatter names are reserved under : + +- +- +- + +## Implement a custom formatter + +To implement a custom formatter, you need to: + +- Create a subclass of , this represents your custom formatter +- Register your custom formatter with + - + - + +Create an extension method to handle this for you: + +:::code language="csharp" source="snippets/logging/console-formatter-custom/ConsoleLoggerExtensions.cs" highlight="11-12"::: + +The `CustomOptions` are defined as follows: + +:::code language="csharp" source="snippets/logging/console-formatter-custom/CustomOptions.cs"::: + +In the preceding code, the options are a subclass of . + +The `AddConsoleFormatter` API: + +- Registers a subclass of `ConsoleFormatter` +- Handles configuration: + - Uses a change token to synchronize updates, based on the [options pattern](options.md), and the [IOptionsMonitor](xref:Microsoft.Extensions.Options.IOptionsMonitor%601) interface + +:::code language="csharp" source="snippets/logging/console-formatter-custom/Program.cs" highlight="11-12"::: + +Define a `CustomerFormatter` subclass of `ConsoleFormatter`: + +:::code language="csharp" source="snippets/logging/console-formatter-custom/CustomFormatter.cs" highlight="24-45"::: + +The preceding `CustomFormatter.Write` API dictates what text gets wrapped around each log message. A standard `ConsoleFormatter` should be able to wrap around scopes, time stamps, and severity level of logs at a minimum. Additionally, you can encode ANSI colors in the log messages, and provide desired indentations as well. The implementation of the `CustomFormatter.Write` lacks these capabilities. + +For inspiration on further customizing formatting, see the existing implementations in the `Microsoft.Extensions.Logging.Console` namespace: + +- [SimpleConsoleFormatter](https://github.com/dotnet/runtime/blob/master/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs). +- [SystemdConsoleFormatter](https://github.com/dotnet/runtime/blob/master/src/libraries/Microsoft.Extensions.Logging.Console/src/SystemdConsoleFormatter.cs) +- [JsonConsoleFormatter](https://github.com/dotnet/runtime/blob/master/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs) + +## Implement custom color formatting + +In order to properly enable color capabilities in your custom logging formatter, you can extend the as it has a property that can be useful for enabling colors in logs. + +Create a `CustomColorOptions` that derives from `SimpleConsoleFormatterOptions`: + +:::code language="csharp" source="snippets/logging/console-formatter-custom/CustomColorOptions.cs" highlight="5"::: + +Next, write some extension methods in a `TextWriterExtensions` class that allow for conveniently embedding ANSI coded colors within formatted log messages: + +:::code language="csharp" source="snippets/logging/console-formatter-custom/TextWriterExtensions.cs"::: + +A custom color formatter that handles applying custom colors could be defined as follows: + +:::code language="csharp" source="snippets/logging/console-formatter-custom/CustomColorFormatter.cs" highlight="15-18,52-65"::: + +When you run the application, the logs will show the `CustomPrefix` message in the color green when `FormatterOptions.ColorBehavior` is `Enabled`. + +## See also + +- [Logging in .NET](logging.md) +- [Implement a custom logging provider in .NET](custom-logging-provider.md) +- [High-performance logging in .NET](high-performance-logging.md) diff --git a/docs/core/extensions/logging.md b/docs/core/extensions/logging.md index 24a28c7a33ab9..78b12af8ab135 100644 --- a/docs/core/extensions/logging.md +++ b/docs/core/extensions/logging.md @@ -525,5 +525,6 @@ class Program - [Logging providers in .NET](logging-providers.md) - [Implement a custom logging provider in .NET](custom-logging-provider.md) +- [Console log formatting](console-log-formatter.md) - [High-performance logging in .NET](high-performance-logging.md) - Logging bugs should be created in the [github.com/dotnet/extensions](https://github.com/dotnet/extensions/issues) repo diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/ConsoleLoggerExtensions.cs b/docs/core/extensions/snippets/logging/console-formatter-custom/ConsoleLoggerExtensions.cs new file mode 100644 index 0000000000000..e60193b3f2616 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/ConsoleLoggerExtensions.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.Logging; +using System; + +namespace Console.ExampleFormatters.Custom +{ + public static class ConsoleLoggerExtensions + { + public static ILoggingBuilder AddCustomFormatter( + this ILoggingBuilder builder, + Action configure) => + builder.AddConsole(options => options.FormatterName = "customName") + .AddConsoleFormatter(configure); + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/CustomColorFormatter.cs b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomColorFormatter.cs new file mode 100644 index 0000000000000..b12e22cc21280 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomColorFormatter.cs @@ -0,0 +1,69 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging.Console; +using Microsoft.Extensions.Options; +using System; +using System.IO; + +namespace Console.ExampleFormatters.Custom +{ + public sealed class CustomColorFormatter : ConsoleFormatter, IDisposable + { + private readonly IDisposable _optionsReloadToken; + private CustomColorOptions _formatterOptions; + + private bool ConsoleColorFormattingEnabled => + _formatterOptions.ColorBehavior == LoggerColorBehavior.Enabled || + _formatterOptions.ColorBehavior == LoggerColorBehavior.Default && + System.Console.IsOutputRedirected == false; + + public CustomColorFormatter(IOptionsMonitor options) + // Case insensitive + : base("customName") => + (_optionsReloadToken, _formatterOptions) = + (options.OnChange(ReloadLoggerOptions), options.CurrentValue); + + private void ReloadLoggerOptions(CustomColorOptions options) => + _formatterOptions = options; + + public override void Write( + in LogEntry logEntry, + IExternalScopeProvider scopeProvider, + TextWriter textWriter) + { + if (logEntry.Exception is null) + { + return; + } + + string message = + logEntry.Formatter( + logEntry.State, logEntry.Exception); + + if (message == null) + { + return; + } + + CustomLogicGoesHere(textWriter); + textWriter.WriteLine(message); + } + + private void CustomLogicGoesHere(TextWriter textWriter) + { + if (ConsoleColorFormattingEnabled) + { + textWriter.WriteWithColor( + _formatterOptions.CustomPrefix, + ConsoleColor.Black, + ConsoleColor.Green); + } + else + { + textWriter.Write(_formatterOptions.CustomPrefix); + } + } + + public void Dispose() => _optionsReloadToken?.Dispose(); + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/CustomColorOptions.cs b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomColorOptions.cs new file mode 100644 index 0000000000000..1f2213893f684 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomColorOptions.cs @@ -0,0 +1,9 @@ +using Microsoft.Extensions.Logging.Console; + +namespace Console.ExampleFormatters.Custom +{ + public class CustomColorOptions : SimpleConsoleFormatterOptions + { + public string CustomPrefix { get; set; } + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/CustomFormatter.cs b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomFormatter.cs new file mode 100644 index 0000000000000..f105838d4891d --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomFormatter.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging.Console; +using Microsoft.Extensions.Options; +using System; +using System.IO; + +namespace Console.ExampleFormatters.Custom +{ + public sealed class CustomFormatter : ConsoleFormatter, IDisposable + { + private readonly IDisposable _optionsReloadToken; + private CustomOptions _formatterOptions; + + public CustomFormatter(IOptionsMonitor options) + // Case insensitive + : base("customName") => + (_optionsReloadToken, _formatterOptions) = + (options.OnChange(ReloadLoggerOptions), options.CurrentValue); + + private void ReloadLoggerOptions(CustomOptions options) => + _formatterOptions = options; + + public override void Write( + in LogEntry logEntry, + IExternalScopeProvider scopeProvider, + TextWriter textWriter) + { + if (logEntry.Exception is null) + { + return; + } + + string message = + logEntry.Formatter( + logEntry.State, logEntry.Exception); + + if (message == null) + { + return; + } + + CustomLogicGoesHere(textWriter); + textWriter.WriteLine(message); + } + + private void CustomLogicGoesHere(TextWriter textWriter) + { + textWriter.Write(_formatterOptions.CustomPrefix); + } + + public void Dispose() => _optionsReloadToken?.Dispose(); + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/CustomOptions.cs b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomOptions.cs new file mode 100644 index 0000000000000..33d491986d576 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/CustomOptions.cs @@ -0,0 +1,9 @@ +using Microsoft.Extensions.Logging.Console; + +namespace Console.ExampleFormatters.Custom +{ + public class CustomOptions : ConsoleFormatterOptions + { + public string CustomPrefix { get; set; } + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/Program.cs b/docs/core/extensions/snippets/logging/console-formatter-custom/Program.cs new file mode 100644 index 0000000000000..b0fef32abae49 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/Program.cs @@ -0,0 +1,22 @@ +using Microsoft.Extensions.Logging; + +namespace Console.ExampleFormatters.Custom +{ + class Program + { + static void Main() + { + using ILoggerFactory loggerFactory = + LoggerFactory.Create(builder => + builder.AddCustomFormatter(options => + options.CustomPrefix = " ~~~~~ ")); + + ILogger logger = loggerFactory.CreateLogger(); + using (logger.BeginScope("TODO: Add logic to enable scopes")) + { + logger.LogInformation("Hello World!"); + logger.LogInformation("TODO: Add logic to enable timestamp and log level info."); + } + } + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/TextWriterExtensions.cs b/docs/core/extensions/snippets/logging/console-formatter-custom/TextWriterExtensions.cs new file mode 100644 index 0000000000000..60f0e00a61278 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/TextWriterExtensions.cs @@ -0,0 +1,87 @@ +using System; +using System.IO; + +namespace Console.ExampleFormatters.Custom +{ + public static class TextWriterExtensions + { + const string DefaultForegroundColor = "\x1B[39m\x1B[22m"; + const string DefaultBackgroundColor = "\x1B[49m"; + + public static void WriteWithColor( + this TextWriter textWriter, + string message, + ConsoleColor? background, + ConsoleColor? foreground) + { + // Order: + // 1. background color + // 2. foreground color + // 3. message + // 4. reset foreground color + // 5. reset background color + + (bool writeBackgroundColor, string backgroundColor) = + (background.HasValue, GetBackgroundColorEscapeCode(background.Value)); + (bool writeForegroundColor, string foregroundColor) = + (foreground.HasValue, GetForegroundColorEscapeCode(foreground.Value)); + + if (writeBackgroundColor) + { + textWriter.Write(backgroundColor); + } + if (writeForegroundColor) + { + textWriter.Write(foregroundColor); + } + + textWriter.WriteLine(message); + + if (writeForegroundColor) + { + textWriter.Write(DefaultForegroundColor); + } + if (writeBackgroundColor) + { + textWriter.Write(DefaultBackgroundColor); + } + } + + static string GetForegroundColorEscapeCode(ConsoleColor color) => + color switch + { + ConsoleColor.Black => "\x1B[30m", + ConsoleColor.DarkRed => "\x1B[31m", + ConsoleColor.DarkGreen => "\x1B[32m", + ConsoleColor.DarkYellow => "\x1B[33m", + ConsoleColor.DarkBlue => "\x1B[34m", + ConsoleColor.DarkMagenta => "\x1B[35m", + ConsoleColor.DarkCyan => "\x1B[36m", + ConsoleColor.Gray => "\x1B[37m", + ConsoleColor.Red => "\x1B[1m\x1B[31m", + ConsoleColor.Green => "\x1B[1m\x1B[32m", + ConsoleColor.Yellow => "\x1B[1m\x1B[33m", + ConsoleColor.Blue => "\x1B[1m\x1B[34m", + ConsoleColor.Magenta => "\x1B[1m\x1B[35m", + ConsoleColor.Cyan => "\x1B[1m\x1B[36m", + ConsoleColor.White => "\x1B[1m\x1B[37m", + + _ => DefaultForegroundColor + }; + + static string GetBackgroundColorEscapeCode(ConsoleColor color) => + color switch + { + ConsoleColor.Black => "\x1B[40m", + ConsoleColor.DarkRed => "\x1B[41m", + ConsoleColor.DarkGreen => "\x1B[42m", + ConsoleColor.DarkYellow => "\x1B[43m", + ConsoleColor.DarkBlue => "\x1B[44m", + ConsoleColor.DarkMagenta => "\x1B[45m", + ConsoleColor.DarkCyan => "\x1B[46m", + ConsoleColor.Gray => "\x1B[47m", + + _ => DefaultBackgroundColor + }; + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-custom/console-formatter-custom.csproj b/docs/core/extensions/snippets/logging/console-formatter-custom/console-formatter-custom.csproj new file mode 100644 index 0000000000000..6e38e3c303f8d --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-custom/console-formatter-custom.csproj @@ -0,0 +1,13 @@ + + + + Exe + net5.0 + Console.ExampleFormatters.Custom + + + + + + + diff --git a/docs/core/extensions/snippets/logging/console-formatter-json/Program.cs b/docs/core/extensions/snippets/logging/console-formatter-json/Program.cs new file mode 100644 index 0000000000000..9d8de3e8e7385 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-json/Program.cs @@ -0,0 +1,28 @@ +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Console.ExampleFormatters.Json +{ + class Program + { + static Task Main(string[] args) => + CreateHostBuilder(args).Build().RunAsync(); + + static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(builder => builder.UseStartup()) + .ConfigureLogging(builder => + builder.AddJsonConsole(options => + { + options.IncludeScopes = false; + options.TimestampFormat = "hh:mm:ss "; + options.JsonWriterOptions = new JsonWriterOptions + { + Indented = true + }; + })); + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-json/Properties/launchSettings.json b/docs/core/extensions/snippets/logging/console-formatter-json/Properties/launchSettings.json new file mode 100644 index 0000000000000..bf164a203e5ac --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-json/Properties/launchSettings.json @@ -0,0 +1,27 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:59449/", + "sslPort": 44370 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "console-formatter-json": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:5001;http://localhost:5000" + } + } +} \ No newline at end of file diff --git a/docs/core/extensions/snippets/logging/console-formatter-json/Startup.cs b/docs/core/extensions/snippets/logging/console-formatter-json/Startup.cs new file mode 100644 index 0000000000000..889116603ead1 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-json/Startup.cs @@ -0,0 +1,52 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Console.ExampleFormatters.Json +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddControllersWithViews(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseExceptionHandler("/Home/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); + } + app.UseHttpsRedirection(); + app.UseStaticFiles(); + + app.UseRouting(); + + app.UseAuthorization(); + + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + }); + } + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-json/appsettings.json b/docs/core/extensions/snippets/logging/console-formatter-json/appsettings.json new file mode 100644 index 0000000000000..ecbfacc4d3460 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-json/appsettings.json @@ -0,0 +1,27 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + }, + "Console": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + }, + "FormatterName": "json", + "FormatterOptions": { + "SingleLine": true, + "IncludeScopes": true, + "TimestampFormat": "HH:mm:ss ", + "UseUtcTimestamp": true, + "JsonWriterOptions": { + "Indented": true + } + } + } + }, + "AllowedHosts": "*" +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-json/console-formatter-json.csproj b/docs/core/extensions/snippets/logging/console-formatter-json/console-formatter-json.csproj new file mode 100644 index 0000000000000..57947a23960d8 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-json/console-formatter-json.csproj @@ -0,0 +1,13 @@ + + + + Exe + net5.0 + Console.ExampleFormatters.Json + + + + + + + diff --git a/docs/core/extensions/snippets/logging/console-formatter-json/example-output.json b/docs/core/extensions/snippets/logging/console-formatter-json/example-output.json new file mode 100644 index 0000000000000..6414fca7f0e99 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-json/example-output.json @@ -0,0 +1,12 @@ +{ + "Timestamp": "09:08:33 ", + "EventId": 0, + "LogLevel": "Information", + "Category": "Microsoft.Hosting.Lifetime", + "Message": "Now listening on: https://localhost:5001", + "State": { + "Message": "Now listening on: https://localhost:5001", + "address": "https://localhost:5001", + "{OriginalFormat}": "Now listening on: {address}" + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-simple/Program.cs b/docs/core/extensions/snippets/logging/console-formatter-simple/Program.cs new file mode 100644 index 0000000000000..c03595cbaa47f --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-simple/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Extensions.Logging; + +namespace Console.ExampleFormatters.Simple +{ + class Program + { + static void Main() + { + using ILoggerFactory loggerFactory = + LoggerFactory.Create(builder => + builder.AddSimpleConsole(options => + { + options.IncludeScopes = true; + options.SingleLine = true; + options.TimestampFormat = "hh:mm:ss "; + })); + + ILogger logger = loggerFactory.CreateLogger(); + using (logger.BeginScope("[scope is enabled]")) + { + logger.LogInformation("Hello World!"); + logger.LogInformation("Logs contain timestamp and log level."); + logger.LogInformation("Each log message is fit in a single line."); + } + } + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-simple/console-formatter-simple.csproj b/docs/core/extensions/snippets/logging/console-formatter-simple/console-formatter-simple.csproj new file mode 100644 index 0000000000000..387194f795f6d --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-simple/console-formatter-simple.csproj @@ -0,0 +1,14 @@ + + + + Exe + net5.0 + Console.ExampleFormatters.Simple + + + + + + + + diff --git a/docs/core/extensions/snippets/logging/console-formatter-systemd/Program.cs b/docs/core/extensions/snippets/logging/console-formatter-systemd/Program.cs new file mode 100644 index 0000000000000..7d29bf39e4775 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-systemd/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.Extensions.Logging; + +namespace Console.ExampleFormatters.Systemd +{ + class Program + { + static void Main() + { + using ILoggerFactory loggerFactory = + LoggerFactory.Create(builder => + builder.AddSystemdConsole(options => + { + options.IncludeScopes = true; + options.TimestampFormat = "hh:mm:ss "; + })); + + ILogger logger = loggerFactory.CreateLogger(); + using (logger.BeginScope("[scope is enabled]")) + { + logger.LogInformation("Hello World!"); + logger.LogInformation("Logs contain timestamp and log level."); + logger.LogInformation("Systemd console logs never provide color options."); + logger.LogInformation("Systemd console logs always appear in a single line."); + } + } + } +} diff --git a/docs/core/extensions/snippets/logging/console-formatter-systemd/console-formatter-systemd.csproj b/docs/core/extensions/snippets/logging/console-formatter-systemd/console-formatter-systemd.csproj new file mode 100644 index 0000000000000..08431434fe220 --- /dev/null +++ b/docs/core/extensions/snippets/logging/console-formatter-systemd/console-formatter-systemd.csproj @@ -0,0 +1,13 @@ + + + + Exe + net5.0 + Console.ExampleFormatters.Systemd + + + + + + + diff --git a/docs/fundamentals/toc.yml b/docs/fundamentals/toc.yml index aab7b63279ec4..3cb5e247fe89f 100644 --- a/docs/fundamentals/toc.yml +++ b/docs/fundamentals/toc.yml @@ -1558,6 +1558,8 @@ items: href: ../core/extensions/custom-logging-provider.md - name: High-performance logging href: ../core/extensions/high-performance-logging.md + - name: Console log formatting + href: ../core/extensions/console-log-formatter.md - name: HostBuilder (generic host) href: ../core/extensions/generic-host.md - name: Data access