Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docfx.json
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,8 @@
"_csharplang/proposals/csharp-9.0/target-typed-conditional-expression.md" : "Target-typed conditional expression",
"_csharplang/proposals/csharp-9.0/target-typed-new.md" : "Target-typed new expressions",
"_csharplang/proposals/csharp-9.0/top-level-statements.md" : "Top-level statements",
"_csharplang/proposals/csharp-9.0/unconstrained-type-parameter-annotations.md" : "Unconstrained type parameter annotations",


"_vblang/spec/introduction.md": "Introduction",
"_vblang/spec/lexical-grammar.md": "Lexical grammar",
Expand Down
5 changes: 5 additions & 0 deletions docs/core/compatibility/3.1-5.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,16 @@ If you're migrating from version 3.1 of .NET Core, ASP.NET Core, or EF Core to v

## Cryptography

- [Default FeedbackSize value for instances created by TripleDES.Create changed](#default-feedbacksize-value-for-instances-created-by-tripledescreate-changed)
- [Instantiating default implementations of cryptographic abstractions is not supported](#instantiating-default-implementations-of-cryptographic-abstractions-is-not-supported)
- [Default TLS cipher suites for .NET on Linux](#default-tls-cipher-suites-for-net-on-linux)
- [System.Security.Cryptography APIs not supported on Blazor WebAssembly](#systemsecuritycryptography-apis-not-supported-on-blazor-webassembly)
- [System.Security.Cryptography.Oid is functionally init-only](#systemsecuritycryptographyoid-is-functionally-init-only)

[!INCLUDE [tripledes-default-feedback-size-change](../../../includes/core-changes/cryptography/5.0/tripledes-default-feedback-size-change.md)]

***

[!INCLUDE [instantiating-default-implementations-of-cryptographic-abstractions-not-supported](../../../includes/core-changes/cryptography/5.0/instantiating-default-implementations-of-cryptographic-abstractions-not-supported.md)]

***
Expand Down
5 changes: 5 additions & 0 deletions docs/core/compatibility/cryptography.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ The following breaking changes are documented on this page:

| Breaking change | Version introduced |
| - | :-: |
| [Default FeedbackSize value for instances created by TripleDES.Create changed](#default-feedbacksize-value-for-instances-created-by-tripledescreate-changed) | 5.0 |
| [Instantiating default implementations of cryptographic abstractions is not supported](#instantiating-default-implementations-of-cryptographic-abstractions-is-not-supported) | 5.0 |
| [Default TLS cipher suites for .NET on Linux](#default-tls-cipher-suites-for-net-on-linux) | 5.0 |
| [System.Security.Cryptography APIs not supported on Blazor WebAssembly](#systemsecuritycryptography-apis-not-supported-on-blazor-webassembly) | 5.0 |
Expand All @@ -22,6 +23,10 @@ The following breaking changes are documented on this page:

## .NET 5.0

[!INCLUDE [tripledes-default-feedback-size-change](../../../includes/core-changes/cryptography/5.0/tripledes-default-feedback-size-change.md)]

***

[!INCLUDE [instantiating-default-implementations-of-cryptographic-abstractions-not-supported](../../../includes/core-changes/cryptography/5.0/instantiating-default-implementations-of-cryptographic-abstractions-not-supported.md)]

***
Expand Down
154 changes: 154 additions & 0 deletions docs/core/extensions/console-log-formatter.md
Original file line number Diff line number Diff line change
@@ -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 <xref:Microsoft.Extensions.Logging.Console.ConsoleLoggerFormat> 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 <xref:Microsoft.Extensions.Options.IOptionsMonitor%601>
- 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 |
|--|--|
| <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Json?displayProperty=nameWithType> | <xref:Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddJsonConsole%2A?displayProperty=nameWithType> |
| <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Simple?displayProperty=nameWithType> | <xref:Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddSimpleConsole%2A?displayProperty=nameWithType> |
| <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Systemd?displayProperty=nameWithType> | <xref:Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddSystemdConsole%2A?displayProperty=nameWithType> |

### 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 <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Simple?displayProperty=nameWithType> 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 <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Systemd?displayProperty=nameWithType> 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 <xref:System.Text.Json.JsonWriterOptions.Indented?displayProperty=nameWithType> 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 <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames>:

- <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Json?displayProperty=nameWithType>
- <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Simple?displayProperty=nameWithType>
- <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterNames.Systemd?displayProperty=nameWithType>

## Implement a custom formatter

To implement a custom formatter, you need to:

- Create a subclass of <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatter>, this represents your custom formatter
- Register your custom formatter with
- <xref:Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddConsole%2A?displayProperty=nameWithType>
- <xref:Microsoft.Extensions.Logging.ConsoleLoggerExtensions.AddConsoleFormatter%60%602(Microsoft.Extensions.Logging.ILoggingBuilder,System.Action{%60%601})?displayProperty=nameWithType>

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 <xref:Microsoft.Extensions.Logging.Console.ConsoleFormatterOptions>.

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<TState>` 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<TState>` 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 <xref:Microsoft.Extensions.Logging.Console.SimpleConsoleFormatterOptions> as it has a <xref:Microsoft.Extensions.Logging.Console.SimpleConsoleFormatterOptions.ColorBehavior?displayProperty=nameWithType> 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)
28 changes: 14 additions & 14 deletions docs/core/extensions/dependency-injection-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ author: IEvangelist
ms.author: dapine
ms.date: 09/23/2020
ms.topic: tutorial
no-loc: [Transient, Scoped, Singleton, Example]
---

# Tutorial: Use dependency injection in .NET
Expand All @@ -22,8 +23,7 @@ In this tutorial, you learn how to:

## Prerequisites

- [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download/dotnet-core) or a later version.
- An Integrated Development Environment (IDE), [Visual Studio, Visual Studio Code, or Visual Studio for Mac](https://visualstudio.microsoft.com) are all valid choices.
- [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download/dotnet-core) or later.
- Familiarity with creating new .NET applications and installing NuGet packages.

## Create a new console application
Expand Down Expand Up @@ -62,25 +62,25 @@ Add the following default implementation for the various operations:

:::code language="csharp" source="snippets/configuration/console-di/DefaultOperation.cs":::

The `DefaultOperation` implements all of the named/marker interfaces and initializes the `OperationId` property to the last four characters of a new globally unique identifier (GUID).
The `DefaultOperation` implements all of the named marker interfaces and initializes the `OperationId` property to the last four characters of a new globally unique identifier (GUID).

## Add service that requires DI

Add the following operation logger object, which acts as a service to your console application:
Add the following operation logger object, which acts as a service to the console app:

*OperationLogger.cs*

:::code language="csharp" source="snippets/configuration/console-di/OperationLogger.cs":::

The `OperationLogger` defines a constructor that requires each of the aforementioned marker interfaces, that is; `ITransientOperation`, `IScopedOperation`, and `ISingletonOperation`. The object exposes a single method that allows the consumer to log the operations with a given `scope` parameter. When invoked, the `LogOperations` method will log each operation's unique identifier with the scope string and message.
The `OperationLogger` defines a constructor that requires each of the aforementioned marker interfaces, that is; `ITransientOperation`, `IScopedOperation`, and `ISingletonOperation`. The object exposes a single method that allows the consumer to log the operations with a given `scope` parameter. When invoked, the `LogOperations` method logs each operation's unique identifier with the scope string and message.

## Register services for DI

Finally, update the *Program.cs* file to match following:
Update *Program.cs* with the following code:

:::code language="csharp" source="snippets/configuration/console-di/Program.cs" range="1-18,35-60" highlight="22-26":::

The application:
The app:

- Creates an <xref:Microsoft.Extensions.Hosting.IHostBuilder> instance with the [default binder settings](generic-host.md#default-builder-settings).
- Configures services and adds them with their corresponding service lifetime.
Expand All @@ -89,7 +89,7 @@ The application:

## Conclusion

The application produces output similar to the following example:
The app displays output similar to the following example:

```console
Scope 1-Call 1 .GetRequiredService<OperationLogger>(): ITransientOperation [ 80f4...Always different ]
Expand All @@ -109,13 +109,13 @@ Scope 2-Call 2 .GetRequiredService<OperationLogger>(): IScopedOperation [ 2bd
Scope 2-Call 2 .GetRequiredService<OperationLogger>(): ISingletonOperation [ 1586...Always the same ]
```

From the application output, you can see that:
From the app output, you can see that:

- Transient operations are always different, meaning a new instance is created with every retrieval of the service.
- Transient operations are always different, a new instance is created with every retrieval of the service.
- Scoped operations change only with a new scope, but are the same instance within a scope.
- Singleton operations are always the same, meaning a new instance is only created once.
- Singleton operations are always the same, a new instance is only created once.

## Next steps
## See also

> [!div class="nextstepaction"]
> [Dependency injection guidelines](dependency-injection-guidelines.md)
* [Dependency injection guidelines](dependency-injection-guidelines.md)
* [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
3 changes: 2 additions & 1 deletion docs/core/extensions/dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ In apps that process requests, scoped services are disposed at the end of the re
When using Entity Framework Core, the <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContext%2A> extension method registers `DbContext` types with a scoped lifetime by default.

> [!NOTE]
> Do ***not*** resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests. It's fine to:
> Do ***not*** resolve a scoped service from a singleton and be careful not to do so indirectly, for example, through a transient service. It may cause the service to have incorrect state when processing subsequent requests. It's fine to:
>
> - Resolve a singleton service from a scoped or transient service.
> - Resolve a scoped service from another scoped or transient service.
Expand Down Expand Up @@ -286,6 +286,7 @@ Scoped services are disposed by the container that created them. If a scoped ser

- [Use dependency injection in .NET](dependency-injection-usage.md)
- [Dependency injection guidelines](dependency-injection-guidelines.md)
- [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection)
- [NDC Conference Patterns for DI app development](https://www.youtube.com/watch?v=x-C-CNBVTaY)
- [Explicit dependencies principle](../../architecture/modern-web-apps-azure/architectural-principles.md#explicit-dependencies)
- [Inversion of control containers and the dependency injection pattern (Martin Fowler)](https://www.martinfowler.com/articles/injection.html)
Expand Down
1 change: 1 addition & 0 deletions docs/core/extensions/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
@@ -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<CustomOptions> configure) =>
builder.AddConsole(options => options.FormatterName = "customName")
.AddConsoleFormatter<CustomFormatter, CustomOptions>(configure);
}
}
Loading