Събитие
Създаване на интелигентни приложения
17.03, 23 ч. - 21.03, 23 ч.
Присъединете се към поредицата срещи, за да изградите мащабируеми AI решения, базирани на реални случаи на употреба с колеги разработчици и експерти.
Регистрирайте се сегаТози браузър вече не се поддържа.
Надстройте до Microsoft Edge, за да се възползвате от най-новите функции, актуализации на защитата и техническа поддръжка.
Logging providers persist logs, except for the Console
provider, which only displays logs as standard output. For example, the Azure Application Insights provider stores logs in Azure Application Insights. Multiple providers can be enabled.
The default .NET Worker app templates:
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateApplicationBuilder(args).Build();
// Application code should start here.
await host.RunAsync();
The preceding code shows the Program
class created with the .NET Worker app templates. The next several sections provide samples based on the .NET Worker app templates, which use the Generic Host.
To override the default set of logging providers added by Host.CreateApplicationBuilder
, call ClearProviders
and add the logging providers you want. For example, the following code:
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
For additional providers, see:
To configure a service that depends on ILogger<T>
, use constructor injection or provide a factory method. The factory method approach is recommended only if there's no other option. For example, consider a service that needs an ILogger<T>
instance provided by DI:
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<IExampleService>(
container => new DefaultExampleService
{
Logger = container.GetRequiredService<ILogger<IExampleService>>()
});
The preceding code is a Func<IServiceProvider, IExampleService> that runs the first time the DI container needs to construct an instance of IExampleService
. You can access any of the registered services in this way.
Microsoft Extensions include the following logging providers as part of the runtime libraries:
The following logging providers are shipped by Microsoft, but not as part of the runtime libraries. They must be installed as additional NuGet packages.
The Console
provider logs output to the console.
The Debug
provider writes log output by using the System.Diagnostics.Debug class, specifically through the Debug.WriteLine method and only when the debugger is attached. The DebugLoggerProvider creates instances of a logger class that implements the ILogger
interface.
The EventSource
provider writes to a cross-platform event source with the name Microsoft-Extensions-Logging
. On Windows, the provider uses ETW.
The dotnet-trace tool is a cross-platform CLI global tool that enables the collection of .NET Core traces of a running process. The tool collects Microsoft.Extensions.Logging.EventSource provider data using a LoggingEventSource.
See dotnet-trace for installation instructions. For a diagnostic tutorial using dotnet-trace
, see Debug high CPU usage in .NET Core.
The EventLog
provider sends log output to the Windows Event Log. Unlike the other providers, the EventLog
provider does not inherit the default non-provider settings. If EventLog
log settings aren't specified, they default to LogLevel.Warning
.
To log events lower than LogLevel.Warning, explicitly set the log level. The following example sets the Event Log default log level to LogLevel.Information:
"Logging": {
"EventLog": {
"LogLevel": {
"Default": "Information"
}
}
}
AddEventLog overloads can pass in EventLogSettings. If null
or not specified, the following default settings are used:
LogName
: "Application"SourceName
: ".NET Runtime"MachineName
: The local machine name is used.The following code changes the SourceName
from the default value of ".NET Runtime"
to CustomLogs
:
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddEventLog(
config => config.SourceName = "CustomLogs");
using IHost host = builder.Build();
host.Run();
The Microsoft.Extensions.Logging.AzureAppServices provider package writes logs to text files in an Azure App Service app's file system and to blob storage in an Azure Storage account.
The provider package isn't included in the runtime libraries. To use the provider, add the provider package to the project.
To configure provider settings, use AzureFileLoggerOptions and AzureBlobLoggerOptions, as shown in the following example:
using Microsoft.Extensions.Logging.AzureAppServices;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args)
builder.Logging.AddAzureWebAppDiagnostics();
builder.Services.Configure<AzureFileLoggerOptions>(options =>
{
options.FileName = "azure-diagnostics-";
options.FileSizeLimit = 50 * 1024;
options.RetainedFileCountLimit = 5;
});
builder.Services.Configure<AzureBlobLoggerOptions>(options =>
{
options.BlobName = "log.txt";
});
using IHost host = builder.Build();
// Application code should start here.
await host.RunAsync();
When deployed to Azure App Service, the app uses the settings in the App Service logs section of the App Service page of the Azure portal. When the following settings are updated, the changes take effect immediately without requiring a restart or redeployment of the app.
The default location for log files is in the D:\home\LogFiles\Application folder. Additional defaults vary by provider:
This provider only logs when the project runs in the Azure environment.
Azure log streaming supports viewing log activity in real-time from:
To configure Azure log streaming:
Navigate to the Log Stream page to view logs. The logged messages are logged with the ILogger
interface.
The Microsoft.Extensions.Logging.ApplicationInsights provider package writes logs to Azure Application Insights. Application Insights is a service that monitors a web app and provides tools for querying and analyzing the telemetry data. If you use this provider, you can query and analyze your logs by using the Application Insights tools.
For more information, see the following resources:
If you plan to develop your own implementation of the ILoggerProvider interface and corresponding custom implementation of ILogger, consider the following points:
An implementation of ILoggerProvider
will create an ILogger
via its ILoggerProvider.CreateLogger method. If your implementation strives to queue logging messages in a non-blocking manner, the messages should first be materialized or the object state that's used to materialize a log entry should be serialized. Doing so avoids potential exceptions from disposed objects.
For more information, see Implement a custom logging provider in .NET.
Here are some third-party logging frameworks that work with various .NET workloads:
Some third-party frameworks can perform semantic logging, also known as structured logging.
Using a third-party framework is similar to using one of the built-in providers:
ILoggerFactory
or ILoggingBuilder
extension method provided by the logging framework.For more information, see each provider's documentation. Third-party logging providers aren't supported by Microsoft.
Обратна връзка за .NET
.NET е проект с отворен код. Изберете връзка, за да предоставите обратна връзка:
Събитие
Създаване на интелигентни приложения
17.03, 23 ч. - 21.03, 23 ч.
Присъединете се към поредицата срещи, за да изградите мащабируеми AI решения, базирани на реални случаи на употреба с колеги разработчици и експерти.
Регистрирайте се сегаОбучение
Модул
Capture Web Application Logs with App Service Diagnostics Logging - Training
Learn about how to capture trace output from your Azure web apps. View a live log stream and download logs files for offline analysis.