├── korebuild-lock.txt ├── korebuild.json ├── CONTRIBUTING.md ├── test ├── Microsoft.Extensions.Logging.Testing.Tests │ ├── Properties │ │ └── AssemlyInfo.cs │ ├── Microsoft.Extensions.Logging.Testing.Tests.csproj │ └── TestTestOutputHelper.cs ├── Microsoft.Extensions.Logging.Analyzer.Test │ ├── xunit.runner.json │ ├── LoggingDiagnosticRunner.cs │ └── Microsoft.Extensions.Logging.Analyzer.Test.csproj ├── Microsoft.Extensions.Logging.Test │ ├── Console │ │ ├── ConsoleContext.cs │ │ ├── ConsoleSink.cs │ │ └── TestConsole.cs │ ├── ProviderAliasAttribute.cs │ ├── TestLoggerBuilder.cs │ ├── NullLoggerFactoryTest.cs │ ├── LogLevelEnumTest.cs │ ├── LoggerBuilderExtensionsTests.cs │ ├── Microsoft.Extensions.Logging.Test.csproj │ ├── LoggingServiceCollectionExtensionsTest.cs │ ├── TestConfiguration.cs │ ├── DebugLoggerTest.cs │ ├── TraceSourceScopeTest.cs │ ├── TestLoggerProvider.cs │ ├── LoggerProviderConfigurationFactoryTest.cs │ ├── NullLoggerTest.cs │ ├── EventIdTest.cs │ ├── TraceSourceLoggerProviderTest.cs │ └── TraceSourceLoggerTest.cs ├── Microsoft.Extensions.Logging.AzureAppServices.Test │ ├── Microsoft.Extensions.Logging.AzureAppServices.Test.csproj │ ├── OptionsWrapperMonitor.cs │ ├── ManualIntervalControl.cs │ ├── TestBlobSink.cs │ ├── TestFileLoggerProvider.cs │ └── WebConfigurationLevelSwitchTests.cs ├── Microsoft.Extensions.Logging.EventSource.Test │ ├── Microsoft.Extensions.Logging.EventSource.Test.csproj │ ├── AssemblyInfo.cs │ └── AzureAppServicesLoggerFactoryExtensionsTests.cs └── Directory.Build.props ├── NuGet.config ├── run.cmd ├── .vsts-pipelines └── builds │ ├── ci-internal.yml │ └── ci-public.yml ├── samples └── SampleApp │ ├── logging.json │ ├── LoggerExtensions.cs │ └── SampleApp.csproj ├── src ├── Directory.Build.props ├── Microsoft.Extensions.Logging.Testing │ ├── BeginScopeContext.cs │ ├── ShortClassNameAttribute.cs │ ├── RetryContext.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Xunit │ │ ├── LogLevelAttribute.cs │ │ ├── LoggedFactDiscoverer.cs │ │ ├── LoggedTestFramework.cs │ │ ├── LoggedTestFrameworkExecutor.cs │ │ ├── LoggedConditionalFactDiscoverer.cs │ │ ├── LoggedTheoryDiscoverer.cs │ │ ├── LoggedTestAssemblyRunner.cs │ │ ├── LoggedTheoryTestCase.cs │ │ ├── LoggedTestCase.cs │ │ ├── LoggedTestMethodRunner.cs │ │ ├── LoggedTestCollectionRunner.cs │ │ ├── LoggedTestClassRunner.cs │ │ ├── LoggedTestCaseRunner.cs │ │ ├── LoggedTheoryTestCaseRunner.cs │ │ └── LoggedConditionalTheoryDiscoverer.cs │ ├── ITestSink.cs │ ├── TestFrameworkFileLoggerAttribute.cs │ ├── TestLoggerProvider.cs │ ├── LoggedTest │ │ ├── ILoggedTest.cs │ │ └── LoggedTest.cs │ ├── WriteContext.cs │ ├── TestLoggerFactory.cs │ ├── TestLoggerOfT.cs │ ├── build │ │ └── Microsoft.Extensions.Logging.Testing.props │ ├── Microsoft.Extensions.Logging.Testing.csproj │ ├── XunitLoggerFactoryExtensions.cs │ ├── TestLogger.cs │ └── TestSink.cs ├── Microsoft.Extensions.Logging.Console │ ├── IConsoleLoggerSettings.cs │ ├── Internal │ │ ├── IAnsiSystemConsole.cs │ │ ├── IConsole.cs │ │ ├── LogMessageEntry.cs │ │ └── WindowsLogConsole.cs │ ├── ConsoleLoggerOptionsSetup.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Microsoft.Extensions.Logging.Console.csproj │ ├── ConsoleLoggerOptions.cs │ ├── ConsoleLoggerSettings.cs │ └── ConsoleLogScope.cs ├── Microsoft.Extensions.Logging │ ├── Properties │ │ └── AssemlyInfo.cs │ ├── DefaultLoggerLevelConfigureOptions.cs │ ├── LoggingBuilder.cs │ ├── ILoggingBuilder.cs │ ├── ProviderAliasAttribute.cs │ ├── StaticFilterOptionsMonitor.cs │ ├── Microsoft.Extensions.Logging.csproj │ ├── LoggerFilterOptions.cs │ ├── ProviderAliasUtilities.cs │ ├── LoggingBuilderExtensions.cs │ ├── LoggerFilterRule.cs │ ├── LoggingServiceCollectionExtensions.cs │ └── LoggerInformation.cs ├── Microsoft.Extensions.Logging.AzureAppServices │ ├── Internal │ │ ├── LogMessage.cs │ │ ├── ForwardingLoggerProvider.cs │ │ ├── SiteConfigurationProvider.cs │ │ ├── ICloudAppendBlob.cs │ │ ├── FileLoggerConfigureOptions.cs │ │ ├── IWebAppContext.cs │ │ ├── BlobLoggerConfigureOptions.cs │ │ ├── BatchLoggerConfigureOptions.cs │ │ ├── WebAppContext.cs │ │ ├── ConfigurationBasedLevelSwitcher.cs │ │ └── BatchingLogger.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Microsoft.Extensions.Logging.AzureAppServices.csproj │ └── AzureBlobLoggerOptions.cs ├── Microsoft.Extensions.Logging.EventLog │ ├── Internal │ │ └── IEventLog.cs │ ├── Microsoft.Extensions.Logging.EventLog.csproj │ ├── WindowsEventLog.cs │ ├── EventLogSettings.cs │ └── EventLogLoggerProvider.cs ├── Microsoft.Extensions.Logging.Configuration │ ├── LoggingConfiguration.cs │ ├── Microsoft.Extensions.Logging.Configuration.csproj │ ├── LoggerProviderOptionsChangeTokenSource.cs │ ├── LoggerProviderConfiguration.cs │ ├── ILoggerProviderConfiguration.cs │ ├── ILoggerProviderConfigurationFactory.cs │ ├── LoggerProviderConfigureOptions.cs │ ├── LoggingBuilderConfigurationExtensions.cs │ ├── LoggerProviderConfigurationExtensions.cs │ ├── LoggingBuilderExtensions.cs │ └── LoggerProviderConfigurationFactory.cs ├── Microsoft.Extensions.Logging.Debug │ ├── Microsoft.Extensions.Logging.Debug.csproj │ ├── DebugLogger.debug.cs │ ├── DebugLoggerProvider.cs │ └── DebugLoggerFactoryExtensions.cs ├── Microsoft.Extensions.Logging.Abstractions │ ├── Properties │ │ ├── AssemblyInfo.cs │ │ └── Resource.Designer.cs │ ├── Internal │ │ └── NullScope.cs │ ├── Microsoft.Extensions.Logging.Abstractions.csproj │ ├── ISupportExternalScope.cs │ ├── ILoggerOfT.cs │ ├── ILoggerProvider.cs │ ├── NullLoggerProvider.cs │ ├── ILoggerFactory.cs │ ├── NullLogger.cs │ ├── NullLoggerFactory.cs │ ├── IExternalScopeProvider.cs │ ├── EventId.cs │ ├── NullLoggerOfT.cs │ ├── LoggerOfT.cs │ ├── LoggerFactoryExtensions.cs │ ├── ILogger.cs │ ├── LogLevel.cs │ └── LoggerExternalScopeProvider.cs ├── Microsoft.Extensions.Logging.EventSource │ ├── Microsoft.Extensions.Logging.EventSource.csproj │ ├── ExceptionInfo.cs │ ├── EventLogFiltersConfigureOptionsChangeSource.cs │ ├── EventLogFiltersConfigureOptions.cs │ └── EventSourceLoggerFactoryExtensions.cs ├── Microsoft.Extensions.Logging.TraceSource │ ├── Microsoft.Extensions.Logging.TraceSource.csproj │ └── TraceSourceScope.cs └── Microsoft.Extensions.Logging.Analyzers │ ├── Microsoft.Extensions.Logging.Analyzers.csproj │ └── Descriptors.cs ├── .appveyor.yml ├── .gitignore ├── NuGetPackageVerifier.json ├── .travis.yml ├── Directory.Build.targets ├── benchmarks └── Logging.Performance │ ├── Logging.Performance.csproj │ ├── LoggingBenchmarkBase.cs │ └── LogValuesBenchmarks.cs ├── Directory.Build.props ├── .gitattributes ├── README.md └── version.props /korebuild-lock.txt: -------------------------------------------------------------------------------- 1 | version:3.0.0-alpha1-20181004.7 2 | commithash:27fabdaf2b1d4753c3d2749581694ca65d78f7f2 3 | -------------------------------------------------------------------------------- /korebuild.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", 3 | "channel": "master" 4 | } 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ====== 3 | 4 | Information on contributing to this repo is in the [Contributing Guide](https://github.com/aspnet/Home/blob/master/CONTRIBUTING.md) in the Home repo. 5 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Testing.Tests/Properties/AssemlyInfo.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Microsoft.Extensions.Logging.Testing; 3 | 4 | [assembly: LogLevel(LogLevel.Trace)] 5 | -------------------------------------------------------------------------------- /NuGet.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Analyzer.Test/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/xunit.runner.schema", 3 | "appDomain": "denied", 4 | "methodDisplay": "method", 5 | "longRunningTestSeconds": 60 6 | } 7 | -------------------------------------------------------------------------------- /run.cmd: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0run.ps1' %*; exit $LASTEXITCODE" 3 | -------------------------------------------------------------------------------- /.vsts-pipelines/builds/ci-internal.yml: -------------------------------------------------------------------------------- 1 | trigger: 2 | - master 3 | - release/* 4 | 5 | resources: 6 | repositories: 7 | - repository: buildtools 8 | type: git 9 | name: aspnet-BuildTools 10 | ref: refs/heads/master 11 | 12 | phases: 13 | - template: .vsts-pipelines/templates/project-ci.yml@buildtools 14 | -------------------------------------------------------------------------------- /samples/SampleApp/logging.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | }, 8 | "Console": 9 | { 10 | "IncludeScopes": "true", 11 | "TimestampFormat": "[HH:mm:ss] ", 12 | "LogToStandardErrorThreshold": "Warning" 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /.vsts-pipelines/builds/ci-public.yml: -------------------------------------------------------------------------------- 1 | trigger: 2 | - master 3 | - release/* 4 | 5 | # See https://github.com/aspnet/BuildTools 6 | resources: 7 | repositories: 8 | - repository: buildtools 9 | type: github 10 | endpoint: DotNet-Bot GitHub Connection 11 | name: aspnet/BuildTools 12 | ref: refs/heads/master 13 | 14 | phases: 15 | - template: .vsts-pipelines/templates/project-ci.yml@buildtools 16 | -------------------------------------------------------------------------------- /src/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | true 6 | logging 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/BeginScopeContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.Testing 5 | { 6 | public class BeginScopeContext 7 | { 8 | public object Scope { get; set; } 9 | 10 | public string LoggerName { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/IConsoleLoggerSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Primitives; 3 | 4 | namespace Microsoft.Extensions.Logging.Console 5 | { 6 | public interface IConsoleLoggerSettings 7 | { 8 | bool IncludeScopes { get; } 9 | 10 | IChangeToken ChangeToken { get; } 11 | 12 | bool TryGetSwitch(string name, out LogLevel level); 13 | 14 | IConsoleLoggerSettings Reload(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/Internal/IAnsiSystemConsole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.Console.Internal 5 | { 6 | public interface IAnsiSystemConsole 7 | { 8 | void Write(string message); 9 | 10 | void WriteLine(string message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.appveyor.yml: -------------------------------------------------------------------------------- 1 | init: 2 | - git config --global core.autocrlf true 3 | branches: 4 | only: 5 | - master 6 | - /^release\/.*$/ 7 | - /^(.*\/)?ci-.*$/ 8 | build_script: 9 | - ps: .\run.ps1 default-build 10 | clone_depth: 1 11 | environment: 12 | global: 13 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true 14 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 15 | ASPNETCORE_TEST_LOG_DIR: $APPVEYOR_BUILD_FOLDER\artifacts\logs 16 | test: 'off' 17 | deploy: 'off' 18 | os: Visual Studio 2017 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/Properties/AssemlyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Configuration, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | [Oo]bj/ 2 | [Bb]in/ 3 | TestResults/ 4 | .nuget/ 5 | _ReSharper.*/ 6 | packages/ 7 | artifacts/ 8 | PublishProfiles/ 9 | *.user 10 | *.suo 11 | *.cache 12 | *.docstates 13 | _ReSharper.* 14 | nuget.exe 15 | *net45.csproj 16 | *net451.csproj 17 | *k10.csproj 18 | *.psess 19 | *.vsp 20 | *.pidb 21 | *.userprefs 22 | *DS_Store 23 | *.ncrunchsolution 24 | *.*sdf 25 | *.ipch 26 | *.sln.ide 27 | project.lock.json 28 | .vs 29 | .build/ 30 | .testPublish/ 31 | global.json 32 | BenchmarkDotNet.Artifacts/ -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/LogMessage.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 7 | { 8 | public struct LogMessage 9 | { 10 | public DateTimeOffset Timestamp { get; set; } 11 | public string Message { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/ShortClassNameAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright(c) .NET Foundation.All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false)] 9 | public class ShortClassNameAttribute : Attribute 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NuGetPackageVerifier.json: -------------------------------------------------------------------------------- 1 | { 2 | "Default": { 3 | "rules": [ 4 | "DefaultCompositeRule" 5 | ], 6 | "packages": { 7 | "Microsoft.Extensions.Logging.Testing": { 8 | "Exclusions": { 9 | "BUILD_ITEMS_FRAMEWORK": { 10 | "*": "Props file intentionally targets any framework since the content is the same for both netstandard2.0 and net461." 11 | } 12 | } 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventLog/Internal/IEventLog.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Diagnostics; 5 | 6 | namespace Microsoft.Extensions.Logging.EventLog.Internal 7 | { 8 | public interface IEventLog 9 | { 10 | int MaxMessageSize { get; } 11 | 12 | void WriteEntry(string message, EventLogEntryType type, int eventID, short category); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/Console/ConsoleContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Test.Console 7 | { 8 | public class ConsoleContext 9 | { 10 | public ConsoleColor? BackgroundColor { get; set; } 11 | 12 | public ConsoleColor? ForegroundColor { get; set; } 13 | 14 | public string Message { get; set; } 15 | } 16 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/Internal/IConsole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Console.Internal 7 | { 8 | public interface IConsole 9 | { 10 | void Write(string message, ConsoleColor? background, ConsoleColor? foreground); 11 | void WriteLine(string message, ConsoleColor? background, ConsoleColor? foreground); 12 | void Flush(); 13 | } 14 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/RetryContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | public class RetryContext 9 | { 10 | internal int Limit { get; set; } 11 | 12 | internal object TestClassInstance { get; set; } 13 | 14 | internal string Reason { get; set; } 15 | 16 | internal int CurrentIteration { get; set; } 17 | } 18 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/ConsoleLoggerOptionsSetup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.Logging.Configuration; 3 | using Microsoft.Extensions.Options; 4 | 5 | namespace Microsoft.Extensions.Logging.Console 6 | { 7 | internal class ConsoleLoggerOptionsSetup : ConfigureFromConfigurationOptions 8 | { 9 | public ConsoleLoggerOptionsSetup(ILoggerProviderConfiguration providerConfiguration) 10 | : base(providerConfiguration.Configuration) 11 | { 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/DefaultLoggerLevelConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Options; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | internal class DefaultLoggerLevelConfigureOptions : ConfigureOptions 9 | { 10 | public DefaultLoggerLevelConfigureOptions(LogLevel level) : base(options => options.MinLevel = level) 11 | { 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/LoggingBuilder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.DependencyInjection; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | internal class LoggingBuilder : ILoggingBuilder 9 | { 10 | public LoggingBuilder(IServiceCollection services) 11 | { 12 | Services = services; 13 | } 14 | 15 | public IServiceCollection Services { get; } 16 | } 17 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggingConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Configuration; 5 | 6 | namespace Microsoft.Extensions.Logging.Configuration 7 | { 8 | internal class LoggingConfiguration 9 | { 10 | public IConfiguration Configuration { get; } 11 | 12 | public LoggingConfiguration(IConfiguration configuration) 13 | { 14 | Configuration = configuration; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/Console/ConsoleSink.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | 7 | namespace Microsoft.Extensions.Logging.Test.Console 8 | { 9 | public class ConsoleSink 10 | { 11 | public List Writes { get; set; } = new List(); 12 | 13 | public void Write(ConsoleContext context) 14 | { 15 | Writes.Add(context); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Debug/Microsoft.Extensions.Logging.Debug.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug output logger provider implementation for Microsoft.Extensions.Logging. This logger logs messages to a debugger monitor by writing messages with System.Diagnostics.Debug.WriteLine(). 5 | netstandard2.0 6 | $(NoWarn);CS1591 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.AzureAppServices.Test/Microsoft.Extensions.Logging.AzureAppServices.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(StandardTestTfms) 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Runtime.CompilerServices; 5 | 6 | [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Runtime.CompilerServices; 5 | 6 | 7 | [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.EventSource.Test/Microsoft.Extensions.Logging.EventSource.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(StandardTestTfms) 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Runtime.CompilerServices; 5 | 6 | [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Testing.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] 7 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/Internal/LogMessageEntry.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Console.Internal 7 | { 8 | public struct LogMessageEntry 9 | { 10 | public string TimeStamp; 11 | public string LevelString; 12 | public ConsoleColor? LevelBackground; 13 | public ConsoleColor? LevelForeground; 14 | public ConsoleColor? MessageColor; 15 | public string Message; 16 | public bool LogAsError; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LogLevelAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false)] 9 | public class LogLevelAttribute : Attribute 10 | { 11 | public LogLevelAttribute(LogLevel logLevel) 12 | { 13 | LogLevel = logLevel; 14 | } 15 | 16 | public LogLevel LogLevel { get; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/ILoggingBuilder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.DependencyInjection; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// An interface for configuring logging providers. 10 | /// 11 | public interface ILoggingBuilder 12 | { 13 | /// 14 | /// Gets the where Logging services are configured. 15 | /// 16 | IServiceCollection Services { get; } 17 | } 18 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Runtime.CompilerServices; 5 | 6 | 7 | [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.AzureAppServices.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/ProviderAliasAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// Test implementation of ProviderAliasAttribute 10 | /// 11 | [AttributeUsage(AttributeTargets.Class)] 12 | public class ProviderAliasAttribute : Attribute 13 | { 14 | public ProviderAliasAttribute(string alias) 15 | { 16 | Alias = alias; 17 | } 18 | 19 | public string Alias { get; } 20 | } 21 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/Microsoft.Extensions.Logging.Configuration.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Configuration support for Microsoft.Extensions.Logging. 5 | netstandard2.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventSource/Microsoft.Extensions.Logging.EventSource.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EventSource/EventListener logger provider implementation for Microsoft.Extensions.Logging. 5 | netstandard2.0 6 | $(PackageTags);EventSource;ETW 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.EventSource.Test/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Xunit; 5 | 6 | // There can only be one EventSource per AppDomain, and when an event is raised through that EventSource, 7 | // all existing listeners that enabled that EventSource will receive the event. 8 | // This makes running EventSourceLogger tests in parallel difficult. We mark this assembly 9 | // with CollectionBehavior.CollectionPerAssembly to ensure that all tests in this assembly are executed serially. 10 | [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)] -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/Internal/NullScope.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Abstractions.Internal 7 | { 8 | /// 9 | /// An empty scope without any logic 10 | /// 11 | public class NullScope : IDisposable 12 | { 13 | public static NullScope Instance { get; } = new NullScope(); 14 | 15 | private NullScope() 16 | { 17 | } 18 | 19 | /// 20 | public void Dispose() 21 | { 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | sudo: false 3 | dist: trusty 4 | env: 5 | global: 6 | - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true 7 | - DOTNET_CLI_TELEMETRY_OPTOUT: 1 8 | - ASPNETCORE_TEST_LOG_DIR: $APPVEYOR_BUILD_FOLDER\artifacts\logs 9 | mono: none 10 | os: 11 | - linux 12 | - osx 13 | osx_image: xcode8.2 14 | addons: 15 | apt: 16 | packages: 17 | - libunwind8 18 | branches: 19 | only: 20 | - master 21 | - /^release\/.*$/ 22 | - /^(.*\/)?ci-.*$/ 23 | before_install: 24 | - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s 25 | /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib 26 | /usr/local/lib/; fi 27 | script: 28 | - ./build.sh 29 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/Microsoft.Extensions.Logging.Abstractions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Logging abstractions for Microsoft.Extensions.Logging. 5 | Commonly used types: 6 | Microsoft.Extensions.Logging.ILogger 7 | Microsoft.Extensions.Logging.ILoggerFactory 8 | Microsoft.Extensions.Logging.ILogger<TCategoryName> 9 | Microsoft.Extensions.Logging.LogLevel 10 | Microsoft.Extensions.Logging.Logger<T> 11 | Microsoft.Extensions.Logging.LoggerMessage 12 | Microsoft.Extensions.Logging.Abstractions.NullLogger 13 | netstandard2.0 14 | $(NoWarn);CS1591 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggerProviderOptionsChangeTokenSource.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Options; 5 | 6 | namespace Microsoft.Extensions.Logging.Configuration 7 | { 8 | /// 9 | public class LoggerProviderOptionsChangeTokenSource : ConfigurationChangeTokenSource 10 | { 11 | /// 12 | public LoggerProviderOptionsChangeTokenSource(ILoggerProviderConfiguration providerConfiguration) : base(providerConfiguration.Configuration) 13 | { 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Debug/DebugLogger.debug.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | // We need to define the DEBUG symbol because we want the logger 5 | // to work even when this package is compiled on release. Otherwise, 6 | // the call to Debug.WriteLine will not be in the release binary 7 | #define DEBUG 8 | 9 | namespace Microsoft.Extensions.Logging.Debug 10 | { 11 | public partial class DebugLogger 12 | { 13 | private void DebugWriteLine(string message, string name) 14 | { 15 | System.Diagnostics.Debug.WriteLine(message, category: name); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/ISupportExternalScope.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging 5 | { 6 | /// 7 | /// Represents a that is able to consume external scope information. 8 | /// 9 | public interface ISupportExternalScope 10 | { 11 | /// 12 | /// Sets external scope information source for logger provider. 13 | /// 14 | /// 15 | void SetScopeProvider(IExternalScopeProvider scopeProvider); 16 | } 17 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggerProviderConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Configuration; 5 | 6 | namespace Microsoft.Extensions.Logging.Configuration 7 | { 8 | internal class LoggerProviderConfiguration : ILoggerProviderConfiguration 9 | { 10 | public LoggerProviderConfiguration(ILoggerProviderConfigurationFactory providerConfigurationFactory) 11 | { 12 | Configuration = providerConfigurationFactory.GetConfiguration(typeof(T)); 13 | } 14 | 15 | public IConfiguration Configuration { get; } 16 | } 17 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/ITestSink.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | 4 | namespace Microsoft.Extensions.Logging.Testing 5 | { 6 | public interface ITestSink 7 | { 8 | event Action MessageLogged; 9 | 10 | event Action ScopeStarted; 11 | 12 | Func WriteEnabled { get; set; } 13 | 14 | Func BeginEnabled { get; set; } 15 | 16 | IProducerConsumerCollection Scopes { get; set; } 17 | 18 | IProducerConsumerCollection Writes { get; set; } 19 | 20 | void Write(WriteContext context); 21 | 22 | void Begin(BeginScopeContext context); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/TestLoggerBuilder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Castle.Core.Logging; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace Microsoft.Extensions.Logging.Test 9 | { 10 | public static class TestLoggerBuilder 11 | { 12 | public static ILoggerFactory Create(Action configure) 13 | { 14 | return new ServiceCollection() 15 | .AddLogging(configure) 16 | .BuildServiceProvider() 17 | .GetRequiredService(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/TestFrameworkFileLoggerAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] 9 | public class TestFrameworkFileLoggerAttribute : Attribute 10 | { 11 | public TestFrameworkFileLoggerAttribute(string tfm, string baseDirectory = null) 12 | { 13 | TFM = tfm; 14 | BaseDirectory = baseDirectory; 15 | } 16 | 17 | public string TFM { get; } 18 | public string BaseDirectory { get; } 19 | } 20 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/TestLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.Testing 5 | { 6 | public class TestLoggerProvider : ILoggerProvider 7 | { 8 | private readonly ITestSink _sink; 9 | 10 | public TestLoggerProvider(ITestSink sink) 11 | { 12 | _sink = sink; 13 | } 14 | 15 | public ILogger CreateLogger(string categoryName) 16 | { 17 | return new TestLogger(categoryName, _sink, enabled: true); 18 | } 19 | 20 | public void Dispose() 21 | { 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/ProviderAliasAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// Defines alias for implementation to be used in filtering rules. 10 | /// 11 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] 12 | public class ProviderAliasAttribute: Attribute 13 | { 14 | public ProviderAliasAttribute(string alias) 15 | { 16 | Alias = alias; 17 | } 18 | 19 | public string Alias { get; } 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.TraceSource/Microsoft.Extensions.Logging.TraceSource.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TraceSource logger provider implementation for Microsoft.Extensions.Logging. This logger logs messages to a trace listener by writing messages with System.Diagnostics.TraceSource.TraceEvent(). 5 | netstandard2.0 6 | $(NoWarn);CS1591 7 | true 8 | logging;tracesource 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventLog/Microsoft.Extensions.Logging.EventLog.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Windows Event Log logger provider implementation for Microsoft.Extensions.Logging. 5 | netstandard2.0;net461 6 | $(NoWarn);CS1591 7 | $(PackageTags);eventlog;windowseventlog 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventSource/ExceptionInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.EventSource 5 | { 6 | /// 7 | /// Represents information about exceptions that is captured by EventSourceLogger 8 | /// 9 | [System.Diagnostics.Tracing.EventData(Name ="ExceptionInfo")] 10 | internal class ExceptionInfo 11 | { 12 | public string TypeName { get; set; } 13 | public string Message { get; set; } 14 | public int HResult { get; set; } 15 | public string VerboseMessage { get; set; } // This is the ToString() of the Exception 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/NullLoggerFactoryTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Xunit; 5 | 6 | namespace Microsoft.Extensions.Logging.Abstractions 7 | { 8 | public class NullLoggerFactoryTest 9 | { 10 | [Fact] 11 | public void Create_GivesSameLogger() 12 | { 13 | // Arrange 14 | var factory = NullLoggerFactory.Instance; 15 | 16 | // Act 17 | var logger1 = factory.CreateLogger("Logger1"); 18 | var logger2 = factory.CreateLogger("Logger2"); 19 | 20 | // Assert 21 | Assert.Same(logger1, logger2); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Testing.Tests/Microsoft.Extensions.Logging.Testing.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | $(StandardTestTfms) 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/ILoggerOfT.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// A generic interface for logging where the category name is derived from the specified 10 | /// type name. 11 | /// Generally used to enable activation of a named from dependency injection. 12 | /// 13 | /// The type who's name is used for the logger category name. 14 | public interface ILogger : ILogger 15 | { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/ILoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// Represents a type that can create instances of . 10 | /// 11 | public interface ILoggerProvider : IDisposable 12 | { 13 | /// 14 | /// Creates a new instance. 15 | /// 16 | /// The category name for messages produced by the logger. 17 | /// 18 | ILogger CreateLogger(string categoryName); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/ILoggerProviderConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Configuration; 5 | 6 | namespace Microsoft.Extensions.Logging.Configuration 7 | { 8 | /// 9 | /// Allows access to configuration section associated with logger provider 10 | /// 11 | /// Type of logger provider to get configuration for 12 | public interface ILoggerProviderConfiguration 13 | { 14 | /// 15 | /// Configuration section for requested logger provider 16 | /// 17 | IConfiguration Configuration { get; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.AzureAppServices.Test/OptionsWrapperMonitor.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices.Test 8 | { 9 | internal class OptionsWrapperMonitor : IOptionsMonitor 10 | { 11 | public OptionsWrapperMonitor(T currentValue) 12 | { 13 | CurrentValue = currentValue; 14 | } 15 | 16 | public IDisposable OnChange(Action listener) 17 | { 18 | return null; 19 | } 20 | 21 | public T Get(string name) => CurrentValue; 22 | 23 | public T CurrentValue { get; } 24 | } 25 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/StaticFilterOptionsMonitor.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace Microsoft.Extensions.Logging 8 | { 9 | internal class StaticFilterOptionsMonitor : IOptionsMonitor 10 | { 11 | public StaticFilterOptionsMonitor(LoggerFilterOptions currentValue) 12 | { 13 | CurrentValue = currentValue; 14 | } 15 | 16 | public IDisposable OnChange(Action listener) => null; 17 | 18 | public LoggerFilterOptions Get(string name) => CurrentValue; 19 | 20 | public LoggerFilterOptions CurrentValue { get; } 21 | } 22 | } -------------------------------------------------------------------------------- /Directory.Build.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | $(MicrosoftNETCoreApp20PackageVersion) 4 | $(MicrosoftNETCoreApp21PackageVersion) 5 | $(MicrosoftNETCoreApp22PackageVersion) 6 | $(NETStandardLibrary20PackageVersion) 7 | 8 | 99.9 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedFactDiscoverer.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Xunit.Abstractions; 5 | using Xunit.Sdk; 6 | 7 | namespace Microsoft.Extensions.Logging.Testing 8 | { 9 | public class LoggedFactDiscoverer : FactDiscoverer 10 | { 11 | public LoggedFactDiscoverer(IMessageSink diagnosticMessageSink) : base(diagnosticMessageSink) 12 | { 13 | } 14 | 15 | protected override IXunitTestCase CreateTestCase(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo factAttribute) 16 | => new LoggedTestCase(DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/ILoggerProviderConfigurationFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Configuration; 6 | 7 | namespace Microsoft.Extensions.Logging.Configuration 8 | { 9 | /// 10 | /// Allows access to configuration section associated with logger provider 11 | /// 12 | public interface ILoggerProviderConfigurationFactory 13 | { 14 | /// 15 | /// Return configuration section associated with logger provider 16 | /// 17 | /// The logger provider type 18 | IConfiguration GetConfiguration(Type providerType); 19 | } 20 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggerProviderConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Options; 5 | 6 | namespace Microsoft.Extensions.Logging.Configuration 7 | { 8 | /// 9 | /// Loads settings for into type. 10 | /// 11 | internal class LoggerProviderConfigureOptions : ConfigureFromConfigurationOptions where TOptions : class 12 | { 13 | public LoggerProviderConfigureOptions(ILoggerProviderConfiguration providerConfiguration) 14 | : base(providerConfiguration.Configuration) 15 | { 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/Microsoft.Extensions.Logging.Console.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Console logger provider implementation for Microsoft.Extensions.Logging. 5 | netstandard2.0 6 | $(NoWarn);CS1591 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/LoggedTest/ILoggedTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Reflection; 6 | using Xunit.Abstractions; 7 | 8 | namespace Microsoft.Extensions.Logging.Testing 9 | { 10 | public interface ILoggedTest : IDisposable 11 | { 12 | ILogger Logger { get; } 13 | 14 | ILoggerFactory LoggerFactory { get; } 15 | 16 | ITestOutputHelper TestOutputHelper { get; } 17 | 18 | // For back compat 19 | IDisposable StartLog(out ILoggerFactory loggerFactory, LogLevel minLogLevel, string testName); 20 | 21 | void Initialize(MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/ForwardingLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 5 | { 6 | internal class ForwardingLoggerProvider : ILoggerProvider 7 | { 8 | private readonly ILoggerFactory _loggerFactory; 9 | 10 | public ForwardingLoggerProvider(ILoggerFactory loggerFactory) 11 | { 12 | _loggerFactory = loggerFactory; 13 | } 14 | 15 | public void Dispose() 16 | { 17 | _loggerFactory.Dispose(); 18 | } 19 | 20 | public ILogger CreateLogger(string categoryName) 21 | { 22 | return _loggerFactory.CreateLogger(categoryName); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/NullLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.Abstractions 5 | { 6 | /// 7 | /// Provider for the . 8 | /// 9 | public class NullLoggerProvider : ILoggerProvider 10 | { 11 | public static NullLoggerProvider Instance { get; } = new NullLoggerProvider(); 12 | 13 | private NullLoggerProvider() 14 | { 15 | } 16 | 17 | /// 18 | public ILogger CreateLogger(string categoryName) 19 | { 20 | return NullLogger.Instance; 21 | } 22 | 23 | /// 24 | public void Dispose() 25 | { 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/WriteContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | public class WriteContext 9 | { 10 | public LogLevel LogLevel { get; set; } 11 | 12 | public EventId EventId { get; set; } 13 | 14 | public object State { get; set; } 15 | 16 | public Exception Exception { get; set; } 17 | 18 | public Func Formatter { get; set; } 19 | 20 | public object Scope { get; set; } 21 | 22 | public string LoggerName { get; set; } 23 | 24 | public string Message 25 | { 26 | get 27 | { 28 | return Formatter(State, Exception); 29 | } 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventSource/EventLogFiltersConfigureOptionsChangeSource.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Logging.EventSource; 5 | using Microsoft.Extensions.Options; 6 | using Microsoft.Extensions.Primitives; 7 | 8 | namespace Microsoft.Extensions.Logging 9 | { 10 | internal class EventLogFiltersConfigureOptionsChangeSource: IOptionsChangeTokenSource 11 | { 12 | private readonly LoggingEventSource _eventSource; 13 | 14 | public EventLogFiltersConfigureOptionsChangeSource(LoggingEventSource eventSource) 15 | { 16 | _eventSource = eventSource; 17 | } 18 | 19 | public IChangeToken GetChangeToken() => _eventSource.GetFilterChangeToken(); 20 | 21 | public string Name { get; } 22 | } 23 | } -------------------------------------------------------------------------------- /benchmarks/Logging.Performance/Logging.Performance.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | Microsoft.Extensions.Logging.Performance 6 | Exe 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/TestLoggerFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | public class TestLoggerFactory : ILoggerFactory 9 | { 10 | private readonly ITestSink _sink; 11 | private readonly bool _enabled; 12 | 13 | public TestLoggerFactory(ITestSink sink, bool enabled) 14 | { 15 | _sink = sink; 16 | _enabled = enabled; 17 | } 18 | 19 | public ILogger CreateLogger(string name) 20 | { 21 | return new TestLogger(name, _sink, _enabled); 22 | } 23 | 24 | public void AddProvider(ILoggerProvider provider) 25 | { 26 | } 27 | 28 | public void Dispose() 29 | { 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/ConsoleLoggerOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.Console 5 | { 6 | public class ConsoleLoggerOptions 7 | { 8 | public bool IncludeScopes { get; set; } 9 | public bool DisableColors { get; set; } 10 | 11 | /// 12 | /// Gets or sets value indicating the minimum level of messaged that would get written to Console.Error. 13 | /// 14 | public LogLevel LogToStandardErrorThreshold { get; set; } = LogLevel.None; 15 | 16 | /// 17 | /// Gets or sets format string used to format timestamp in logging messages. Defaults to null 18 | /// 19 | public string TimestampFormat { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.EventSource.Test/AzureAppServicesLoggerFactoryExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | // // Copyright (c) .NET Foundation. All rights reserved. 2 | // // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Xunit; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices.Test 8 | { 9 | public class LoggerFactoryExtensionsTests 10 | { 11 | [Fact] 12 | public void BuilderExtensionAddsSingleSetOfServicesWhenCalledTwice() 13 | { 14 | var serviceCollection = new ServiceCollection(); 15 | serviceCollection.AddLogging(builder => builder.AddEventSourceLogger()); 16 | var count = serviceCollection.Count; 17 | serviceCollection.AddLogging(builder => builder.AddEventSourceLogger()); 18 | 19 | Assert.Equal(count, serviceCollection.Count); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventSource/EventLogFiltersConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Logging.EventSource; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace Microsoft.Extensions.Logging 8 | { 9 | internal class EventLogFiltersConfigureOptions : IConfigureOptions 10 | { 11 | private readonly LoggingEventSource _eventSource; 12 | 13 | public EventLogFiltersConfigureOptions(LoggingEventSource eventSource) 14 | { 15 | _eventSource = eventSource; 16 | } 17 | 18 | public void Configure(LoggerFilterOptions options) 19 | { 20 | foreach (var rule in _eventSource.GetFilterRules()) 21 | { 22 | options.Rules.Add(rule); 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Microsoft .NET Extensions 12 | https://github.com/aspnet/Logging 13 | git 14 | $(MSBuildThisFileDirectory) 15 | $(MSBuildThisFileDirectory)build\Key.snk 16 | true 17 | true 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/SiteConfigurationProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.IO; 5 | using Microsoft.Extensions.Configuration; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 8 | { 9 | public class SiteConfigurationProvider 10 | { 11 | public static IConfiguration GetAzureLoggingConfiguration(IWebAppContext context) 12 | { 13 | var settingsFolder = Path.Combine(context.HomeFolder, "site", "diagnostics"); 14 | var settingsFile = Path.Combine(settingsFolder, "settings.json"); 15 | 16 | return new ConfigurationBuilder() 17 | .AddEnvironmentVariables() 18 | .AddJsonFile(settingsFile, optional: true, reloadOnChange: true) 19 | .Build(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/LoggedTest/LoggedTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Reflection; 5 | using Xunit.Abstractions; 6 | 7 | namespace Microsoft.Extensions.Logging.Testing 8 | { 9 | public class LoggedTest : LoggedTestBase 10 | { 11 | // Obsolete but keeping for back compat 12 | public LoggedTest(ITestOutputHelper output = null) : base (output) { } 13 | 14 | public ITestSink TestSink { get; set; } 15 | 16 | public override void Initialize(MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper) 17 | { 18 | base.Initialize(methodInfo, testMethodArguments, testOutputHelper); 19 | 20 | TestSink = new TestSink(); 21 | LoggerFactory.AddProvider(new TestLoggerProvider(TestSink)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/Microsoft.Extensions.Logging.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Logging infrastructure default implementation for Microsoft.Extensions.Logging. 5 | netstandard2.0 6 | $(NoWarn);CS1591 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/LogLevelEnumTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using Xunit; 8 | 9 | namespace Microsoft.Extensions.Logging.Test 10 | { 11 | public class LogLevelEnumTest 12 | { 13 | [Fact] 14 | public static void EnumStartsAtZero() 15 | { 16 | Assert.Equal(0, GetEnumValues().Min()); 17 | } 18 | 19 | [Fact] 20 | public static void EnumValuesAreUniqueAndConsecutive() 21 | { 22 | var values = GetEnumValues(); 23 | values.Sort(); 24 | Assert.Equal(new[] { 0, 1, 2, 3, 4, 5, 6 }, values); 25 | } 26 | 27 | private static List GetEnumValues() 28 | { 29 | return Enum.GetValues(typeof(LogLevel)).Cast().ToList(); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Analyzer.Test/LoggingDiagnosticRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Analyzer.Testing; 7 | using Microsoft.CodeAnalysis; 8 | using Microsoft.CodeAnalysis.Diagnostics; 9 | 10 | namespace Microsoft.Extensions.Logging.Analyzer 11 | { 12 | public class LoggingDiagnosticRunner : DiagnosticAnalyzerRunner 13 | { 14 | public LoggingDiagnosticRunner(DiagnosticAnalyzer analyzer) 15 | { 16 | Analyzer = analyzer; 17 | } 18 | 19 | public DiagnosticAnalyzer Analyzer { get; } 20 | 21 | public Task GetDiagnosticsAsync(string source, string[] additionalEnabledDiagnostics) 22 | { 23 | return GetDiagnosticsAsync(sources: new[] { source }, Analyzer, additionalEnabledDiagnostics); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/ICloudAppendBlob.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.IO; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 10 | { 11 | /// 12 | /// Represents an append blob, a type of blob where blocks of data are always committed to the end of the blob. 13 | /// 14 | public interface ICloudAppendBlob 15 | { 16 | /// 17 | /// Initiates an asynchronous operation to open a stream for writing to the blob. 18 | /// 19 | /// A object of type that represents the asynchronous operation. 20 | Task AppendAsync(ArraySegment data, CancellationToken cancellationToken); 21 | } 22 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/LoggerFilterOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | public class LoggerFilterOptions 9 | { 10 | /// 11 | /// Gets or sets value indicating whether logging scopes are being captured. Defaults to true 12 | /// 13 | public bool CaptureScopes { get; set; } = true; 14 | 15 | /// 16 | /// Gets or sets the minimum level of log messages if none of the rules match. 17 | /// 18 | public LogLevel MinLevel { get; set; } 19 | 20 | /// 21 | /// Gets the collection of used for filtering log messages. 22 | /// 23 | public IList Rules { get; } = new List(); 24 | } 25 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/ConsoleLoggerSettings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using Microsoft.Extensions.Primitives; 7 | 8 | namespace Microsoft.Extensions.Logging.Console 9 | { 10 | public class ConsoleLoggerSettings : IConsoleLoggerSettings 11 | { 12 | public IChangeToken ChangeToken { get; set; } 13 | 14 | public bool IncludeScopes { get; set; } 15 | 16 | public bool DisableColors { get; set; } 17 | 18 | public IDictionary Switches { get; set; } = new Dictionary(); 19 | 20 | public IConsoleLoggerSettings Reload() 21 | { 22 | return this; 23 | } 24 | 25 | public bool TryGetSwitch(string name, out LogLevel level) 26 | { 27 | return Switches.TryGetValue(name, out level); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestFramework.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Reflection; 5 | using Xunit.Abstractions; 6 | using Xunit.Sdk; 7 | 8 | namespace Microsoft.Extensions.Logging.Testing 9 | { 10 | public class LoggedTestFramework : XunitTestFramework 11 | { 12 | public LoggedTestFramework(IMessageSink messageSink) : base(messageSink) 13 | { 14 | } 15 | 16 | protected override ITestFrameworkDiscoverer CreateDiscoverer(IAssemblyInfo assemblyInfo) 17 | { 18 | return new LoggedTestFrameworkDiscoverer(assemblyInfo, SourceInformationProvider, DiagnosticMessageSink); 19 | } 20 | 21 | protected override ITestFrameworkExecutor CreateExecutor(AssemblyName assemblyName) 22 | { 23 | return new LoggedTestFrameworkExecutor(assemblyName, SourceInformationProvider, DiagnosticMessageSink); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.doc diff=astextplain 2 | *.DOC diff=astextplain 3 | *.docx diff=astextplain 4 | *.DOCX diff=astextplain 5 | *.dot diff=astextplain 6 | *.DOT diff=astextplain 7 | *.pdf diff=astextplain 8 | *.PDF diff=astextplain 9 | *.rtf diff=astextplain 10 | *.RTF diff=astextplain 11 | 12 | *.jpg binary 13 | *.png binary 14 | *.gif binary 15 | 16 | *.cs text=auto diff=csharp 17 | *.vb text=auto 18 | *.resx text=auto 19 | *.c text=auto 20 | *.cpp text=auto 21 | *.cxx text=auto 22 | *.h text=auto 23 | *.hxx text=auto 24 | *.py text=auto 25 | *.rb text=auto 26 | *.java text=auto 27 | *.html text=auto 28 | *.htm text=auto 29 | *.css text=auto 30 | *.scss text=auto 31 | *.sass text=auto 32 | *.less text=auto 33 | *.js text=auto 34 | *.lisp text=auto 35 | *.clj text=auto 36 | *.sql text=auto 37 | *.php text=auto 38 | *.lua text=auto 39 | *.m text=auto 40 | *.asm text=auto 41 | *.erl text=auto 42 | *.fs text=auto 43 | *.fsx text=auto 44 | *.hs text=auto 45 | 46 | *.csproj text=auto 47 | *.vbproj text=auto 48 | *.fsproj text=auto 49 | *.dbproj text=auto 50 | *.sln text=auto eol=crlf 51 | *.sh text=auto eol=lf 52 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/FileLoggerConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.IO; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 9 | { 10 | public class FileLoggerConfigureOptions : BatchLoggerConfigureOptions, IConfigureOptions 11 | { 12 | private readonly IWebAppContext _context; 13 | 14 | public FileLoggerConfigureOptions(IConfiguration configuration, IWebAppContext context) 15 | : base(configuration, "AzureDriveEnabled") 16 | { 17 | _context = context; 18 | } 19 | 20 | public void Configure(AzureFileLoggerOptions options) 21 | { 22 | base.Configure(options); 23 | options.LogDirectory = Path.Combine(_context.HomeFolder, "LogFiles", "Application"); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /test/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netcoreapp2.2 6 | $(DeveloperBuildTestTfms) 7 | 8 | $(StandardTestTfms);net461 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.AzureAppServices.Test/ManualIntervalControl.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.Extensions.Logging.AzureAppServices.Test 7 | { 8 | internal class ManualIntervalControl 9 | { 10 | 11 | private TaskCompletionSource _pauseCompletionSource = new TaskCompletionSource(); 12 | private TaskCompletionSource _resumeCompletionSource; 13 | 14 | public Task Pause => _pauseCompletionSource.Task; 15 | 16 | public void Resume() 17 | { 18 | _pauseCompletionSource = new TaskCompletionSource(); 19 | _resumeCompletionSource.SetResult(null); 20 | } 21 | 22 | public async Task IntervalAsync() 23 | { 24 | _resumeCompletionSource = new TaskCompletionSource(); 25 | _pauseCompletionSource.SetResult(null); 26 | 27 | await _resumeCompletionSource.Task; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/IWebAppContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 5 | { 6 | /// 7 | /// Represents an Azure WebApp context 8 | /// 9 | public interface IWebAppContext 10 | { 11 | /// 12 | /// Gets the path to the home folder if running in Azure WebApp 13 | /// 14 | string HomeFolder { get; } 15 | 16 | /// 17 | /// Gets the name of site if running in Azure WebApp 18 | /// 19 | string SiteName { get; } 20 | 21 | /// 22 | /// Gets the id of site if running in Azure WebApp 23 | /// 24 | string SiteInstanceId { get; } 25 | 26 | /// 27 | /// Gets a value indicating whether or new we're in an Azure WebApp 28 | /// 29 | bool IsRunningInAzureWebApp { get; } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.AzureAppServices.Test/TestBlobSink.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.Extensions.Logging.AzureAppServices.Internal; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices.Test 8 | { 9 | internal class TestBlobSink : BlobLoggerProvider 10 | { 11 | internal ManualIntervalControl IntervalControl { get; } = new ManualIntervalControl(); 12 | 13 | public TestBlobSink(Func blobReferenceFactory) : base( 14 | new OptionsWrapperMonitor(new AzureBlobLoggerOptions() 15 | { 16 | ApplicationInstanceId = "42", 17 | ApplicationName = "appname", 18 | BlobName = "filename", 19 | IsEnabled = true 20 | }), 21 | blobReferenceFactory) 22 | { 23 | } 24 | 25 | protected override Task IntervalAsync(TimeSpan interval, CancellationToken cancellationToken) 26 | { 27 | return IntervalControl.IntervalAsync(); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Testing.Tests/TestTestOutputHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Text; 6 | using Xunit.Abstractions; 7 | 8 | namespace Microsoft.Extensions.Logging.Testing.Tests 9 | { 10 | public class TestTestOutputHelper : ITestOutputHelper 11 | { 12 | private StringBuilder _output = new StringBuilder(); 13 | 14 | public bool Throw { get; set; } 15 | 16 | public string Output => _output.ToString(); 17 | 18 | public void WriteLine(string message) 19 | { 20 | if (Throw) 21 | { 22 | throw new Exception("Boom!"); 23 | } 24 | _output.AppendLine(message); 25 | } 26 | 27 | public void WriteLine(string format, params object[] args) 28 | { 29 | if (Throw) 30 | { 31 | throw new Exception("Boom!"); 32 | } 33 | _output.AppendLine(string.Format(format, args)); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggingBuilderConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.DependencyInjection.Extensions; 5 | 6 | namespace Microsoft.Extensions.Logging.Configuration 7 | { 8 | /// 9 | /// Extension methods for setting up logging services in an . 10 | /// 11 | public static class LoggingBuilderConfigurationExtensions 12 | { 13 | /// 14 | /// Adds services required to consume or 15 | /// 16 | public static void AddConfiguration(this ILoggingBuilder builder) 17 | { 18 | builder.Services.TryAddSingleton(); 19 | builder.Services.TryAddSingleton(typeof(ILoggerProviderConfiguration<>), typeof(LoggerProviderConfiguration<>)); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Analyzer.Test/Microsoft.Extensions.Logging.Analyzer.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(StandardTestTfms) 5 | LoggingAnalyzers 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/TestLoggerOfT.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | public class TestLogger : ILogger 9 | { 10 | private readonly ILogger _logger; 11 | 12 | public TestLogger(TestLoggerFactory factory) 13 | { 14 | _logger = factory.CreateLogger(); 15 | } 16 | 17 | public IDisposable BeginScope(TState state) 18 | { 19 | return _logger.BeginScope(state); 20 | } 21 | 22 | public bool IsEnabled(LogLevel logLevel) 23 | { 24 | return _logger.IsEnabled(logLevel); 25 | } 26 | 27 | public void Log( 28 | LogLevel logLevel, 29 | EventId eventId, 30 | TState state, 31 | Exception exception, 32 | Func formatter) 33 | { 34 | _logger.Log(logLevel, eventId, state, exception, formatter); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/ILoggerFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// Represents a type used to configure the logging system and create instances of from 10 | /// the registered s. 11 | /// 12 | public interface ILoggerFactory : IDisposable 13 | { 14 | /// 15 | /// Creates a new instance. 16 | /// 17 | /// The category name for messages produced by the logger. 18 | /// The . 19 | ILogger CreateLogger(string categoryName); 20 | 21 | /// 22 | /// Adds an to the logging system. 23 | /// 24 | /// The . 25 | void AddProvider(ILoggerProvider provider); 26 | } 27 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/NullLogger.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.Abstractions.Internal; 6 | 7 | namespace Microsoft.Extensions.Logging.Abstractions 8 | { 9 | /// 10 | /// Minimalistic logger that does nothing. 11 | /// 12 | public class NullLogger : ILogger 13 | { 14 | public static NullLogger Instance { get; } = new NullLogger(); 15 | 16 | private NullLogger() 17 | { 18 | } 19 | 20 | /// 21 | public IDisposable BeginScope(TState state) 22 | { 23 | return NullScope.Instance; 24 | } 25 | 26 | /// 27 | public bool IsEnabled(LogLevel logLevel) 28 | { 29 | return false; 30 | } 31 | 32 | /// 33 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 34 | { 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/NullLoggerFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging.Abstractions 5 | { 6 | /// 7 | /// An used to create instance of 8 | /// that logs nothing. 9 | /// 10 | public class NullLoggerFactory : ILoggerFactory 11 | { 12 | public static readonly NullLoggerFactory Instance = new NullLoggerFactory(); 13 | 14 | /// 15 | /// 16 | /// This returns a instance which logs nothing. 17 | /// 18 | public ILogger CreateLogger(string name) 19 | { 20 | return NullLogger.Instance; 21 | } 22 | 23 | /// 24 | /// 25 | /// This method ignores the parameter and does nothing. 26 | /// 27 | public void AddProvider(ILoggerProvider provider) 28 | { 29 | } 30 | 31 | public void Dispose() 32 | { 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestFrameworkExecutor.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | using Xunit.Abstractions; 7 | using Xunit.Sdk; 8 | 9 | namespace Microsoft.Extensions.Logging.Testing 10 | { 11 | public class LoggedTestFrameworkExecutor : XunitTestFrameworkExecutor 12 | { 13 | public LoggedTestFrameworkExecutor(AssemblyName assemblyName, ISourceInformationProvider sourceInformationProvider, IMessageSink diagnosticMessageSink) 14 | : base(assemblyName, sourceInformationProvider, diagnosticMessageSink) 15 | { 16 | } 17 | 18 | protected override async void RunTestCases(IEnumerable testCases, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions) 19 | { 20 | using (var assemblyRunner = new LoggedTestAssemblyRunner(TestAssembly, testCases, DiagnosticMessageSink, executionMessageSink, executionOptions)) 21 | { 22 | await assemblyRunner.RunAsync(); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Microsoft.Extensions.Logging.AzureAppServices.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Logger implementation to support Azure App Services 'Diagnostics logs' and 'Log stream' features. 5 | netstandard2.0 6 | $(NoWarn);CS1591 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventLog/WindowsEventLog.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Diagnostics; 5 | using Microsoft.Extensions.Logging.EventLog.Internal; 6 | 7 | namespace Microsoft.Extensions.Logging.EventLog 8 | { 9 | public class WindowsEventLog : IEventLog 10 | { 11 | // https://msdn.microsoft.com/EN-US/library/windows/desktop/aa363679.aspx 12 | private const int MaximumMessageSize = 31839; 13 | 14 | public WindowsEventLog(string logName, string machineName, string sourceName) 15 | { 16 | DiagnosticsEventLog = new System.Diagnostics.EventLog(logName, machineName, sourceName); 17 | } 18 | 19 | public System.Diagnostics.EventLog DiagnosticsEventLog { get; } 20 | 21 | public int MaxMessageSize 22 | { 23 | get 24 | { 25 | return MaximumMessageSize; 26 | } 27 | } 28 | 29 | public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) 30 | { 31 | DiagnosticsEventLog.WriteEvent(new EventInstance(eventID, category, type), message); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedConditionalFactDiscoverer.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.AspNetCore.Testing.xunit; 5 | using Xunit.Abstractions; 6 | using Xunit.Sdk; 7 | 8 | namespace Microsoft.Extensions.Logging.Testing 9 | { 10 | public class LoggedConditionalFactDiscoverer : LoggedFactDiscoverer 11 | { 12 | private readonly IMessageSink _diagnosticMessageSink; 13 | 14 | public LoggedConditionalFactDiscoverer(IMessageSink diagnosticMessageSink) : base(diagnosticMessageSink) 15 | { 16 | _diagnosticMessageSink = diagnosticMessageSink; 17 | } 18 | 19 | protected override IXunitTestCase CreateTestCase(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo factAttribute) 20 | { 21 | var skipReason = testMethod.EvaluateSkipConditions(); 22 | return skipReason != null 23 | ? new SkippedTestCase(skipReason, _diagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod) 24 | : base.CreateTestCase(discoveryOptions, testMethod, factAttribute); 25 | } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Debug/DebugLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Debug 7 | { 8 | /// 9 | /// The provider for the . 10 | /// 11 | [ProviderAlias("Debug")] 12 | public class DebugLoggerProvider : ILoggerProvider 13 | { 14 | private readonly Func _filter; 15 | 16 | public DebugLoggerProvider() 17 | { 18 | _filter = null; 19 | } 20 | 21 | /// 22 | /// Initializes a new instance of the class. 23 | /// 24 | /// The function used to filter events based on the log level. 25 | public DebugLoggerProvider(Func filter) 26 | { 27 | _filter = filter; 28 | } 29 | 30 | /// 31 | public ILogger CreateLogger(string name) 32 | { 33 | return new DebugLogger(name, _filter); 34 | } 35 | 36 | public void Dispose() 37 | { 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/BlobLoggerConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 8 | { 9 | public class BlobLoggerConfigureOptions : BatchLoggerConfigureOptions, IConfigureOptions 10 | { 11 | private readonly IConfiguration _configuration; 12 | private readonly IWebAppContext _context; 13 | 14 | public BlobLoggerConfigureOptions(IConfiguration configuration, IWebAppContext context) 15 | : base(configuration, "AzureBlobEnabled") 16 | { 17 | _configuration = configuration; 18 | _context = context; 19 | } 20 | 21 | public void Configure(AzureBlobLoggerOptions options) 22 | { 23 | base.Configure(options); 24 | options.ContainerUrl = _configuration.GetSection("APPSETTING_DIAGNOSTICS_AZUREBLOBCONTAINERSASURL")?.Value; 25 | options.ApplicationName = _context.SiteName; 26 | options.ApplicationInstanceId = _context.SiteInstanceId; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/IExternalScopeProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// Represents a storage of common scope data. 10 | /// 11 | public interface IExternalScopeProvider 12 | { 13 | /// 14 | /// Executes callback for each currently active scope objects in order of creation. 15 | /// All callbacks are guaranteed to be called inline from this method. 16 | /// 17 | /// The callback to be executed for every scope object 18 | /// The state object to be passed into the callback 19 | /// 20 | void ForEachScope(Action callback, TState state); 21 | 22 | /// 23 | /// Adds scope object to the list 24 | /// 25 | /// The scope object 26 | /// The token that removes scope on dispose. 27 | IDisposable Push(object state); 28 | } 29 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/ProviderAliasUtilities.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Reflection; 6 | 7 | namespace Microsoft.Extensions.Logging 8 | { 9 | internal class ProviderAliasUtilities 10 | { 11 | private const string AliasAttibuteTypeFullName = "Microsoft.Extensions.Logging.ProviderAliasAttribute"; 12 | private const string AliasAttibuteAliasProperty = "Alias"; 13 | 14 | internal static string GetAlias(Type providerType) 15 | { 16 | foreach (var attribute in providerType.GetTypeInfo().GetCustomAttributes(inherit: false)) 17 | { 18 | if (attribute.GetType().FullName == AliasAttibuteTypeFullName) 19 | { 20 | var valueProperty = attribute 21 | .GetType() 22 | .GetProperty(AliasAttibuteAliasProperty, BindingFlags.Public | BindingFlags.Instance); 23 | 24 | if (valueProperty != null) 25 | { 26 | return valueProperty.GetValue(attribute) as string; 27 | } 28 | } 29 | } 30 | 31 | return null; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/BatchLoggerConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 8 | { 9 | public class BatchLoggerConfigureOptions : IConfigureOptions 10 | { 11 | private readonly IConfiguration _configuration; 12 | private readonly string _isEnabledKey; 13 | 14 | public BatchLoggerConfigureOptions(IConfiguration configuration, string isEnabledKey) 15 | { 16 | _configuration = configuration; 17 | _isEnabledKey = isEnabledKey; 18 | } 19 | 20 | public void Configure(BatchingLoggerOptions options) 21 | { 22 | options.IsEnabled = TextToBoolean(_configuration.GetSection(_isEnabledKey)?.Value); 23 | } 24 | 25 | private static bool TextToBoolean(string text) 26 | { 27 | if (string.IsNullOrEmpty(text) || 28 | !bool.TryParse(text, out var result)) 29 | { 30 | result = false; 31 | } 32 | 33 | return result; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTheoryDiscoverer.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using Xunit.Abstractions; 6 | using Xunit.Sdk; 7 | 8 | namespace Microsoft.Extensions.Logging.Testing 9 | { 10 | public class LoggedTheoryDiscoverer : TheoryDiscoverer 11 | { 12 | public LoggedTheoryDiscoverer(IMessageSink diagnosticMessageSink) : base(diagnosticMessageSink) 13 | { 14 | } 15 | 16 | protected override IEnumerable CreateTestCasesForDataRow( 17 | ITestFrameworkDiscoveryOptions discoveryOptions, 18 | ITestMethod testMethod, 19 | IAttributeInfo theoryAttribute, 20 | object[] dataRow) 21 | => new[] { new LoggedTestCase(DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod, dataRow) }; 22 | 23 | protected override IEnumerable CreateTestCasesForTheory( 24 | ITestFrameworkDiscoveryOptions discoveryOptions, 25 | ITestMethod testMethod, 26 | IAttributeInfo theoryAttribute) 27 | => new[] { new LoggedTheoryTestCase(DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod) }; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/LoggerBuilderExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Xunit; 6 | 7 | namespace Microsoft.Extensions.Logging.Test 8 | { 9 | public class LoggerBuilderExtensionsTests 10 | { 11 | [Fact] 12 | public void AddConsole_BuilderExtensionAddsSingleSetOfServicesWhenCalledTwice() 13 | { 14 | var serviceCollection = new ServiceCollection(); 15 | serviceCollection.AddLogging(builder => builder.AddConsole()); 16 | var count = serviceCollection.Count; 17 | serviceCollection.AddLogging(builder => builder.AddConsole()); 18 | 19 | Assert.Equal(count, serviceCollection.Count); 20 | } 21 | 22 | [Fact] 23 | public void AddDebug_BuilderExtensionAddsSingleSetOfServicesWhenCalledTwice() 24 | { 25 | var serviceCollection = new ServiceCollection(); 26 | serviceCollection.AddLogging(builder => builder.AddDebug()); 27 | var count = serviceCollection.Count; 28 | serviceCollection.AddLogging(builder => builder.AddDebug()); 29 | 30 | Assert.Equal(count, serviceCollection.Count); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/Microsoft.Extensions.Logging.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(StandardTestTfms) 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/WebAppContext.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 7 | { 8 | /// 9 | /// Represents the default implementation of . 10 | /// 11 | public class WebAppContext : IWebAppContext 12 | { 13 | /// 14 | /// Gets the default instance of the WebApp context. 15 | /// 16 | public static WebAppContext Default { get; } = new WebAppContext(); 17 | 18 | private WebAppContext() { } 19 | 20 | /// 21 | public string HomeFolder { get; } = Environment.GetEnvironmentVariable("HOME"); 22 | 23 | /// 24 | public string SiteName { get; } = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME"); 25 | 26 | /// 27 | public string SiteInstanceId { get; } = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"); 28 | 29 | /// 30 | public bool IsRunningInAzureWebApp => !string.IsNullOrEmpty(HomeFolder) && 31 | !string.IsNullOrEmpty(SiteName); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/LoggingServiceCollectionExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Linq; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Xunit; 7 | 8 | namespace Microsoft.Extensions.Logging.Test 9 | { 10 | public class LoggingServiceCollectionExtensionsTest 11 | { 12 | [Fact] 13 | public void AddLogging_WrapsServiceCollection() 14 | { 15 | var services = new ServiceCollection(); 16 | 17 | var callbackCalled = false; 18 | var loggerBuilder = services.AddLogging(builder => 19 | { 20 | callbackCalled = true; 21 | Assert.Same(services, builder.Services); 22 | }); 23 | Assert.True(callbackCalled); 24 | } 25 | 26 | [Fact] 27 | public void ClearProviders_RemovesAllProvidersFromServiceCollection() 28 | { 29 | var services = new ServiceCollection(); 30 | services.AddLogging(builder => builder.AddConsole()); 31 | 32 | services.AddLogging(builder => builder.ClearProviders()); 33 | 34 | Assert.Empty(services.Where(desctriptor => desctriptor.ServiceType == typeof(ILoggerProvider))); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/TestConfiguration.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.Configuration.Json; 9 | 10 | namespace Microsoft.Extensions.Logging.Test 11 | { 12 | internal class TestConfiguration : JsonConfigurationProvider 13 | { 14 | private Func _json; 15 | public TestConfiguration(JsonConfigurationSource source, Func json) 16 | : base(source) 17 | { 18 | _json = json; 19 | } 20 | 21 | public override void Load() 22 | { 23 | var stream = new MemoryStream(); 24 | var writer = new StreamWriter(stream); 25 | writer.Write(_json()); 26 | writer.Flush(); 27 | stream.Seek(0, SeekOrigin.Begin); 28 | Load(stream); 29 | } 30 | 31 | public static ConfigurationRoot Create(Func getJson) 32 | { 33 | var provider = new TestConfiguration(new JsonConfigurationSource { Optional = true }, getJson); 34 | return new ConfigurationRoot(new List { provider }); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.AzureAppServices.Test/TestFileLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Microsoft.Extensions.Logging.AzureAppServices.Internal; 8 | 9 | namespace Microsoft.Extensions.Logging.AzureAppServices.Test 10 | { 11 | internal class TestFileLoggerProvider : FileLoggerProvider 12 | { 13 | internal ManualIntervalControl IntervalControl { get; } = new ManualIntervalControl(); 14 | 15 | public TestFileLoggerProvider( 16 | string path, 17 | string fileName = "LogFile.", 18 | int maxFileSize = 32_000, 19 | int maxRetainedFiles = 100) 20 | : base(new OptionsWrapperMonitor(new AzureFileLoggerOptions() 21 | { 22 | LogDirectory = path, 23 | FileName = fileName, 24 | FileSizeLimit = maxFileSize, 25 | RetainedFileCountLimit = maxRetainedFiles, 26 | IsEnabled = true 27 | })) 28 | { 29 | } 30 | 31 | protected override Task IntervalAsync(TimeSpan interval, CancellationToken cancellationToken) 32 | { 33 | return IntervalControl.IntervalAsync(); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/AzureBlobLoggerOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.AzureAppServices.Internal; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices 8 | { 9 | /// 10 | /// Options for Azure diagnostics blob logging. 11 | /// 12 | public class AzureBlobLoggerOptions: BatchingLoggerOptions 13 | { 14 | private string _blobName = "applicationLog.txt"; 15 | 16 | /// 17 | /// Gets or sets the last section of log blob name. 18 | /// Defaults to "applicationLog.txt". 19 | /// 20 | public string BlobName 21 | { 22 | get { return _blobName; } 23 | set 24 | { 25 | if (string.IsNullOrEmpty(value)) 26 | { 27 | throw new ArgumentException(nameof(value), $"{nameof(BlobName)} must be non-empty string."); 28 | } 29 | _blobName = value; 30 | } 31 | } 32 | 33 | internal string ContainerUrl { get; set; } 34 | 35 | internal string ApplicationName { get; set; } 36 | 37 | internal string ApplicationInstanceId { get; set; } 38 | } 39 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/LoggingBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.DependencyInjection.Extensions; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace Microsoft.Extensions.Logging 9 | { 10 | /// 11 | /// Extension methods for setting up logging services in an . 12 | /// 13 | public static class LoggingBuilderExtensions 14 | { 15 | public static ILoggingBuilder SetMinimumLevel(this ILoggingBuilder builder, LogLevel level) 16 | { 17 | builder.Services.Add(ServiceDescriptor.Singleton>( 18 | new DefaultLoggerLevelConfigureOptions(level))); 19 | return builder; 20 | } 21 | 22 | public static ILoggingBuilder AddProvider(this ILoggingBuilder builder, ILoggerProvider provider) 23 | { 24 | builder.Services.AddSingleton(provider); 25 | return builder; 26 | } 27 | 28 | public static ILoggingBuilder ClearProviders(this ILoggingBuilder builder) 29 | { 30 | builder.Services.RemoveAll(); 31 | return builder; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/DebugLoggerTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.Debug; 6 | using Xunit; 7 | 8 | namespace Microsoft.Extensions.Logging 9 | { 10 | public class DebugLoggerTest 11 | { 12 | [Fact] 13 | public void CallingBeginScopeOnLogger_ReturnsNonNullableInstance() 14 | { 15 | // Arrange 16 | var logger = new DebugLogger("Test"); 17 | 18 | // Act 19 | var disposable = logger.BeginScope("Scope1"); 20 | 21 | // Assert 22 | Assert.NotNull(disposable); 23 | } 24 | 25 | [Fact] 26 | public void CallingLogWithCurlyBracesAfterFormatter_DoesNotThrow() 27 | { 28 | // Arrange 29 | var logger = new DebugLogger("Test"); 30 | var message = "{test string}"; 31 | 32 | // Act 33 | logger.Log(LogLevel.Debug, 0, message, null, (s, e) => s); 34 | } 35 | 36 | [Fact] 37 | public static void IsEnabledReturnsCorrectValue() 38 | { 39 | // Arrange 40 | var logger = new DebugLogger("Test"); 41 | 42 | // Assert 43 | Assert.False(logger.IsEnabled(LogLevel.None)); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Analyzers/Microsoft.Extensions.Logging.Analyzers.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Analyzer package for Microsoft.Extensions.Logging. 5 | $(ExperimentalVersionPrefix) 6 | $(ExperimentalVersionSuffix) 7 | $(ExperimentalPackageVersion) 8 | false 9 | netstandard1.3 10 | $(NoWarn);CS1591 11 | false 12 | analyzers/dotnet/cs/ 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestAssemblyRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit.Abstractions; 8 | using Xunit.Sdk; 9 | 10 | namespace Microsoft.Extensions.Logging.Testing 11 | { 12 | public class LoggedTestAssemblyRunner : XunitTestAssemblyRunner 13 | { 14 | public LoggedTestAssemblyRunner( 15 | ITestAssembly testAssembly, 16 | IEnumerable testCases, 17 | IMessageSink diagnosticMessageSink, 18 | IMessageSink executionMessageSink, 19 | ITestFrameworkExecutionOptions executionOptions) 20 | : base(testAssembly, testCases, diagnosticMessageSink, executionMessageSink, executionOptions) 21 | { 22 | } 23 | 24 | protected override Task RunTestCollectionAsync( 25 | IMessageBus messageBus, 26 | ITestCollection testCollection, 27 | IEnumerable testCases, 28 | CancellationTokenSource cancellationTokenSource) 29 | => new LoggedTestCollectionRunner(testCollection, testCases, DiagnosticMessageSink, messageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), cancellationTokenSource).RunAsync(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/build/Microsoft.Extensions.Logging.Testing.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(ASPNETCORE_TEST_LOG_DIR) 5 | $(RepositoryRoot)artifacts\logs\ 6 | 7 | 8 | 11 | 12 | 13 | <_Parameter1>Microsoft.Extensions.Logging.Testing.LoggedTestFramework 14 | <_Parameter2>Microsoft.Extensions.Logging.Testing 15 | 16 | 17 | 18 | <_Parameter1>$(TargetFramework) 19 | <_Parameter2 Condition="'$(LoggingTestingDisableFileLogging)' != 'true'">$(LoggingTestingFileLoggingDirectory) 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggerProviderConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.DependencyInjection.Extensions; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace Microsoft.Extensions.Logging.Configuration 9 | { 10 | /// 11 | /// Provides a set of helpers to initialize options objects from logger provider configuration. 12 | /// 13 | public static class LoggerProviderOptions 14 | { 15 | /// 16 | /// Indicates that settings for should be loaded into type. 17 | /// 18 | /// The options class 19 | /// The provider class 20 | public static void RegisterProviderOptions(IServiceCollection services) where TOptions : class 21 | { 22 | services.TryAddEnumerable(ServiceDescriptor.Singleton, LoggerProviderConfigureOptions>()); 23 | services.TryAddEnumerable(ServiceDescriptor.Singleton, LoggerProviderOptionsChangeTokenSource>()); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTheoryTestCase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit.Abstractions; 8 | using Xunit.Sdk; 9 | 10 | namespace Microsoft.Extensions.Logging.Testing 11 | { 12 | public class LoggedTheoryTestCase : XunitTheoryTestCase 13 | { 14 | [Obsolete("Called by the de-serializer; should only be called by deriving classes for de-serialization purposes")] 15 | public LoggedTheoryTestCase() : base() 16 | { 17 | } 18 | 19 | public LoggedTheoryTestCase( 20 | IMessageSink diagnosticMessageSink, 21 | TestMethodDisplay defaultMethodDisplay, 22 | ITestMethod testMethod) 23 | : base(diagnosticMessageSink, defaultMethodDisplay, testMethod) 24 | { 25 | } 26 | 27 | public override Task RunAsync( 28 | IMessageSink diagnosticMessageSink, 29 | IMessageBus messageBus, 30 | object[] constructorArguments, 31 | ExceptionAggregator aggregator, 32 | CancellationTokenSource cancellationTokenSource) 33 | => new LoggedTheoryTestCaseRunner(this, DisplayName, SkipReason, constructorArguments, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource).RunAsync(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.TraceSource/TraceSourceScope.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Microsoft.Extensions.Logging.TraceSource 8 | { 9 | /// 10 | /// Provides an IDisposable that represents a logical operation scope based on System.Diagnostics LogicalOperationStack 11 | /// 12 | public class TraceSourceScope : IDisposable 13 | { 14 | // To detect redundant calls 15 | private bool _isDisposed; 16 | 17 | /// 18 | /// Pushes state onto the LogicalOperationStack by calling 19 | /// 20 | /// 21 | /// The state. 22 | public TraceSourceScope(object state) 23 | { 24 | Trace.CorrelationManager.StartLogicalOperation(state); 25 | } 26 | 27 | /// 28 | /// Pops a state off the LogicalOperationStack by calling 29 | /// 30 | /// 31 | public void Dispose() 32 | { 33 | if (!_isDisposed) 34 | { 35 | Trace.CorrelationManager.StopLogicalOperation(); 36 | _isDisposed = true; 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventLog/EventLogSettings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.EventLog.Internal; 6 | 7 | namespace Microsoft.Extensions.Logging.EventLog 8 | { 9 | /// 10 | /// Settings for . 11 | /// 12 | public class EventLogSettings 13 | { 14 | /// 15 | /// Name of the event log. If null or not specified, "Application" is the default. 16 | /// 17 | public string LogName { get; set; } 18 | 19 | /// 20 | /// Name of the event log source. If null or not specified, "Application" is the default. 21 | /// 22 | public string SourceName { get; set; } 23 | 24 | /// 25 | /// Name of the machine having the event log. If null or not specified, local machine is the default. 26 | /// 27 | public string MachineName { get; set; } 28 | 29 | /// 30 | /// The function used to filter events based on the log level. 31 | /// 32 | public Func Filter { get; set; } 33 | 34 | /// 35 | /// For unit testing purposes only. 36 | /// 37 | public IEventLog EventLog { get; set; } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestCase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit.Abstractions; 8 | using Xunit.Sdk; 9 | 10 | namespace Microsoft.Extensions.Logging.Testing 11 | { 12 | public class LoggedTestCase : XunitTestCase 13 | { 14 | [Obsolete("Called by the de-serializer; should only be called by deriving classes for de-serialization purposes")] 15 | public LoggedTestCase() : base() 16 | { 17 | } 18 | 19 | public LoggedTestCase( 20 | IMessageSink diagnosticMessageSink, 21 | TestMethodDisplay defaultMethodDisplay, 22 | ITestMethod testMethod, 23 | object[] testMethodArguments = null) 24 | : base(diagnosticMessageSink, defaultMethodDisplay, testMethod, testMethodArguments) 25 | { 26 | } 27 | 28 | public override Task RunAsync( 29 | IMessageSink diagnosticMessageSink, 30 | IMessageBus messageBus, 31 | object[] constructorArguments, 32 | ExceptionAggregator aggregator, 33 | CancellationTokenSource cancellationTokenSource) 34 | => new LoggedTestCaseRunner(this, DisplayName, SkipReason, constructorArguments, TestMethodArguments, messageBus, aggregator, cancellationTokenSource).RunAsync(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/TraceSourceScopeTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Diagnostics; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Xunit; 7 | 8 | namespace Microsoft.Extensions.Logging.Test 9 | { 10 | public class TraceSourceScopeTest 11 | { 12 | #if NET461 13 | [Fact] 14 | public static void DiagnosticsScope_PushesAndPops_LogicalOperationStack() 15 | { 16 | // Arrange 17 | var baseState = "base"; 18 | Trace.CorrelationManager.StartLogicalOperation(baseState); 19 | var state = "1337state7331"; 20 | 21 | var factory = TestLoggerBuilder.Create(builder => 22 | builder.AddTraceSource(new SourceSwitch("TestSwitch"), new ConsoleTraceListener())); 23 | 24 | var logger = factory.CreateLogger("Test"); 25 | 26 | // Act 27 | var a = Trace.CorrelationManager.LogicalOperationStack.Peek(); 28 | var scope = logger.BeginScope(state); 29 | var b = Trace.CorrelationManager.LogicalOperationStack.Peek(); 30 | scope.Dispose(); 31 | var c = Trace.CorrelationManager.LogicalOperationStack.Peek(); 32 | 33 | // Assert 34 | Assert.Same(a, c); 35 | Assert.Same(state, b); 36 | } 37 | #elif NETCOREAPP2_2 38 | #else 39 | #error Target framework needs to be updated 40 | #endif 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/TestLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.Testing; 6 | 7 | namespace Microsoft.Extensions.Logging.Test 8 | { 9 | #pragma warning disable CS0436 // Type conflicts with imported type 10 | [ProviderAlias("TestLogger")] 11 | #pragma warning restore CS0436 // Type conflicts with imported type 12 | public class TestLoggerProvider : ILoggerProvider 13 | { 14 | private readonly Func _filter; 15 | 16 | public TestLoggerProvider(TestSink testSink, bool isEnabled) : 17 | this(testSink, _ => isEnabled) 18 | { 19 | } 20 | 21 | public TestLoggerProvider(TestSink testSink, Func filter) 22 | { 23 | Sink = testSink; 24 | _filter = filter; 25 | } 26 | 27 | public TestSink Sink { get; } 28 | 29 | public bool DisposeCalled { get; private set; } 30 | 31 | public ILogger CreateLogger(string categoryName) 32 | { 33 | return new TestLogger(categoryName, Sink, _filter); 34 | } 35 | 36 | public void Dispose() 37 | { 38 | DisposeCalled = true; 39 | } 40 | } 41 | 42 | public class TestLoggerProvider2 : TestLoggerProvider 43 | { 44 | public TestLoggerProvider2(TestSink testSink) : base(testSink, true) 45 | { 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/EventId.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging 5 | { 6 | public readonly struct EventId 7 | { 8 | public static implicit operator EventId(int i) 9 | { 10 | return new EventId(i); 11 | } 12 | 13 | public static bool operator ==(EventId left, EventId right) 14 | { 15 | return left.Equals(right); 16 | } 17 | 18 | public static bool operator !=(EventId left, EventId right) 19 | { 20 | return !left.Equals(right); 21 | } 22 | 23 | public EventId(int id, string name = null) 24 | { 25 | Id = id; 26 | Name = name; 27 | } 28 | 29 | public int Id { get; } 30 | public string Name { get; } 31 | 32 | public override string ToString() 33 | { 34 | return Name ?? Id.ToString(); 35 | } 36 | 37 | public bool Equals(EventId other) 38 | { 39 | return Id == other.Id; 40 | } 41 | 42 | public override bool Equals(object obj) 43 | { 44 | if (ReferenceEquals(null, obj)) 45 | { 46 | return false; 47 | } 48 | 49 | return obj is EventId eventId && Equals(eventId); 50 | } 51 | 52 | public override int GetHashCode() 53 | { 54 | return Id; 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/NullLoggerOfT.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Abstractions 7 | { 8 | /// 9 | /// Minimalistic logger that does nothing. 10 | /// 11 | public class NullLogger : ILogger 12 | { 13 | public static readonly NullLogger Instance = new NullLogger(); 14 | 15 | /// 16 | public IDisposable BeginScope(TState state) 17 | { 18 | return NullDisposable.Instance; 19 | } 20 | 21 | /// 22 | /// 23 | /// This method ignores the parameters and does nothing. 24 | /// 25 | public void Log( 26 | LogLevel logLevel, 27 | EventId eventId, 28 | TState state, 29 | Exception exception, 30 | Func formatter) 31 | { 32 | } 33 | 34 | /// 35 | public bool IsEnabled(LogLevel logLevel) 36 | { 37 | return false; 38 | } 39 | 40 | private class NullDisposable : IDisposable 41 | { 42 | public static readonly NullDisposable Instance = new NullDisposable(); 43 | 44 | public void Dispose() 45 | { 46 | // intentionally does nothing 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /benchmarks/Logging.Performance/LoggingBenchmarkBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Performance 7 | { 8 | public class LoggingBenchmarkBase 9 | { 10 | protected static readonly Action NoArgumentTraceMessage = LoggerMessage.Define(LogLevel.Trace, 0, "Message"); 11 | protected static readonly Action NoArgumentErrorMessage = LoggerMessage.Define(LogLevel.Error, 0, "Message"); 12 | 13 | protected static readonly Action TwoArgumentTraceMessage = LoggerMessage.Define(LogLevel.Trace, 0, "Message {Argument1} {Argument2}"); 14 | protected static readonly Action TwoArgumentErrorMessage = LoggerMessage.Define(LogLevel.Error, 0, "Message {Argument1} {Argument2}"); 15 | 16 | protected static Exception Exception = ((Func)(() => { 17 | try 18 | { 19 | throw new Exception(); 20 | } 21 | catch (Exception ex) 22 | { 23 | return ex; 24 | } 25 | }))(); 26 | 27 | public class LoggerProvider: ILoggerProvider 28 | where T: ILogger, new() 29 | { 30 | public void Dispose() 31 | { 32 | } 33 | 34 | public ILogger CreateLogger(string categoryName) 35 | { 36 | return new T(); 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestMethodRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit.Abstractions; 8 | using Xunit.Sdk; 9 | 10 | namespace Microsoft.Extensions.Logging.Testing 11 | { 12 | public class LoggedTestMethodRunner : XunitTestMethodRunner 13 | { 14 | private IMessageSink DiagnosticMessageSink { get; } 15 | private object[] ConstructorArguments { get; } 16 | 17 | public LoggedTestMethodRunner( 18 | ITestMethod testMethod, 19 | IReflectionTypeInfo @class, 20 | IReflectionMethodInfo method, 21 | IEnumerable testCases, 22 | IMessageSink diagnosticMessageSink, 23 | IMessageBus messageBus, 24 | ExceptionAggregator aggregator, 25 | CancellationTokenSource cancellationTokenSource, 26 | object[] constructorArguments) 27 | : base(testMethod, @class, method, testCases, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource, constructorArguments) 28 | { 29 | DiagnosticMessageSink = diagnosticMessageSink; 30 | ConstructorArguments = constructorArguments; 31 | } 32 | 33 | protected override Task RunTestCaseAsync(IXunitTestCase testCase) 34 | => testCase.RunAsync(DiagnosticMessageSink, MessageBus, ConstructorArguments, new ExceptionAggregator(Aggregator), CancellationTokenSource); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestCollectionRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Xunit.Abstractions; 8 | using Xunit.Sdk; 9 | 10 | namespace Microsoft.Extensions.Logging.Testing 11 | { 12 | public class LoggedTestCollectionRunner : XunitTestCollectionRunner 13 | { 14 | private readonly IMessageSink _diagnosticMessageSink; 15 | 16 | public LoggedTestCollectionRunner( 17 | ITestCollection testCollection, 18 | IEnumerable testCases, 19 | IMessageSink diagnosticMessageSink, 20 | IMessageBus messageBus, 21 | ITestCaseOrderer testCaseOrderer, 22 | ExceptionAggregator aggregator, 23 | CancellationTokenSource cancellationTokenSource) 24 | : base(testCollection, testCases, diagnosticMessageSink, messageBus, testCaseOrderer, aggregator, cancellationTokenSource) 25 | { 26 | // Base class doesn't expose this, so capture it here. 27 | _diagnosticMessageSink = diagnosticMessageSink; 28 | } 29 | 30 | protected override Task RunTestClassAsync(ITestClass testClass, IReflectionTypeInfo @class, IEnumerable testCases) 31 | => new LoggedTestClassRunner(testClass, @class, testCases, _diagnosticMessageSink, MessageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), CancellationTokenSource, CollectionFixtureMappings).RunAsync(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggingBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Logging.Configuration; 7 | using Microsoft.Extensions.Options; 8 | 9 | namespace Microsoft.Extensions.Logging 10 | { 11 | /// 12 | /// Extension methods for setting up logging services in an . 13 | /// 14 | public static class LoggingBuilderExtensions 15 | { 16 | /// 17 | /// Configures from an instance of . 18 | /// 19 | /// The to use. 20 | /// The to add. 21 | /// The builder. 22 | public static ILoggingBuilder AddConfiguration(this ILoggingBuilder builder, IConfiguration configuration) 23 | { 24 | builder.AddConfiguration(); 25 | 26 | builder.Services.AddSingleton>(new LoggerFilterConfigureOptions(configuration)); 27 | builder.Services.AddSingleton>(new ConfigurationChangeTokenSource(configuration)); 28 | 29 | builder.Services.AddSingleton(new LoggingConfiguration(configuration)); 30 | 31 | return builder; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestClassRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using Xunit.Abstractions; 9 | using Xunit.Sdk; 10 | 11 | namespace Microsoft.Extensions.Logging.Testing 12 | { 13 | public class LoggedTestClassRunner : XunitTestClassRunner 14 | { 15 | public LoggedTestClassRunner( 16 | ITestClass testClass, 17 | IReflectionTypeInfo @class, 18 | IEnumerable testCases, 19 | IMessageSink diagnosticMessageSink, 20 | IMessageBus messageBus, 21 | ITestCaseOrderer testCaseOrderer, 22 | ExceptionAggregator aggregator, 23 | CancellationTokenSource cancellationTokenSource, 24 | IDictionary collectionFixtureMappings) 25 | : base(testClass, @class, testCases, diagnosticMessageSink, messageBus, testCaseOrderer, aggregator, cancellationTokenSource, collectionFixtureMappings) 26 | { 27 | } 28 | 29 | protected override Task RunTestMethodAsync( 30 | ITestMethod testMethod, 31 | IReflectionMethodInfo method, 32 | IEnumerable testCases, 33 | object[] constructorArguments) 34 | => new LoggedTestMethodRunner(testMethod, Class, method, testCases, DiagnosticMessageSink, MessageBus, new ExceptionAggregator(Aggregator), CancellationTokenSource, constructorArguments).RunAsync(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Logging 2 | ======= 3 | 4 | **This GitHub project has been archived.** Ongoing development on this project can be found in . 5 | 6 | Common logging abstractions and a few implementations. Refer to the [wiki](https://github.com/aspnet/Logging/wiki) for more information 7 | 8 | This project is part of ASP.NET Core. You can find samples, documentation and getting started instructions for ASP.NET Core at the [AspNetCore](https://github.com/aspnet/AspNetCore) repo. 9 | 10 | ## Providers 11 | 12 | Community projects adapt _Microsoft.Extensions.Logging_ for use with different back-ends. 13 | 14 | * [Sentry](https://github.com/getsentry/sentry-dotnet) - provider for the [Sentry](https://github.com/getsentry/sentry) service 15 | * [Serilog](https://github.com/serilog/serilog-framework-logging) - provider for the Serilog library 16 | * [elmah.io](https://github.com/elmahio/Elmah.Io.Extensions.Logging) - provider for the elmah.io service 17 | * [Loggr](https://github.com/imobile3/Loggr.Extensions.Logging) - provider for the Loggr service 18 | * [NLog](https://github.com/NLog/NLog.Extensions.Logging) - provider for the NLog library 19 | * [Graylog](https://github.com/mattwcole/gelf-extensions-logging) - provider for the Graylog service 20 | * [Sharpbrake](https://github.com/airbrake/sharpbrake#microsoftextensionslogging-integration) - provider for the Airbrake notifier 21 | * [KissLog.net](https://github.com/catalingavan/KissLog-net) - provider for the KissLog.net service 22 | 23 | ## Building from source 24 | 25 | To run a complete build on command line only, execute `build.cmd` or `build.sh` without arguments. See [developer documentation](https://github.com/aspnet/Home/wiki) for more details. 26 | -------------------------------------------------------------------------------- /samples/SampleApp/LoggerExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging; 6 | 7 | namespace SampleApp 8 | { 9 | internal static class LoggerExtensions 10 | { 11 | private static Func _purchaseOrderScope; 12 | private static Action _programStarting; 13 | private static Action _programStopping; 14 | 15 | static LoggerExtensions() 16 | { 17 | _purchaseOrderScope = LoggerMessage.DefineScope("PO:{PurchaseOrder}"); 18 | _programStarting = LoggerMessage.Define(LogLevel.Information, 1, "Starting at '{StartTime}' and 0x{Hello:X} is hex of 42"); 19 | _programStopping = LoggerMessage.Define(LogLevel.Information, 2, "Stopping at '{StopTime}'"); 20 | } 21 | 22 | public static IDisposable PurchaseOrderScope(this ILogger logger, string purchaseOrder) 23 | { 24 | return _purchaseOrderScope(logger, purchaseOrder); 25 | } 26 | 27 | public static void ProgramStarting(this ILogger logger, DateTimeOffset startTime, int hello, Exception exception = null) 28 | { 29 | _programStarting(logger, startTime, hello, exception); 30 | } 31 | 32 | public static void ProgramStopping(this ILogger logger, DateTimeOffset stopTime, Exception exception = null) 33 | { 34 | _programStopping(logger, stopTime, exception); 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/LoggerProviderConfigurationFactoryTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Linq; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.Configuration.Memory; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.Logging.Configuration; 9 | using Microsoft.Extensions.Logging.Console; 10 | using Xunit; 11 | 12 | namespace Microsoft.Extensions.Logging.Test 13 | { 14 | public class LoggerProviderConfigurationFactoryTest 15 | { 16 | [Fact] 17 | public void ChangeTokenFiresWhenSectionAdded() 18 | { 19 | var callbackCalled = false; 20 | var source = new MemoryConfigurationSource(); 21 | var configuration = new ConfigurationBuilder().Add(source).Build(); 22 | var provider = (MemoryConfigurationProvider) configuration.Providers.Single(); 23 | 24 | var serviceCollection = new ServiceCollection(); 25 | serviceCollection.AddLogging(builder => builder.AddConfiguration(configuration)); 26 | var serviceProvider = serviceCollection.BuildServiceProvider(); 27 | 28 | var loggerProviderConfiguration = serviceProvider.GetService>(); 29 | loggerProviderConfiguration.Configuration.GetReloadToken().RegisterChangeCallback(o => callbackCalled = true, null); 30 | 31 | provider.Add("Console:IncludeScopes", "false"); 32 | configuration.Reload(); 33 | 34 | Assert.True(callbackCalled); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventLog/EventLogLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.EventLog 7 | { 8 | /// 9 | /// The provider for the . 10 | /// 11 | [ProviderAlias("EventLog")] 12 | public class EventLogLoggerProvider : ILoggerProvider, ISupportExternalScope 13 | { 14 | private readonly EventLogSettings _settings; 15 | 16 | private IExternalScopeProvider _scopeProvider; 17 | 18 | /// 19 | /// Initializes a new instance of the class. 20 | /// 21 | public EventLogLoggerProvider() 22 | : this(settings: null) 23 | { 24 | } 25 | 26 | /// 27 | /// Initializes a new instance of the class. 28 | /// 29 | /// The . 30 | public EventLogLoggerProvider(EventLogSettings settings) 31 | { 32 | _settings = settings; 33 | } 34 | 35 | /// 36 | public ILogger CreateLogger(string name) 37 | { 38 | return new EventLogLogger(name, _settings ?? new EventLogSettings()); 39 | } 40 | 41 | public void Dispose() 42 | { 43 | } 44 | 45 | public void SetScopeProvider(IExternalScopeProvider scopeProvider) 46 | { 47 | _scopeProvider = scopeProvider; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /samples/SampleApp/SampleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net461;netcoreapp2.2 5 | Exe 6 | 7 | 8 | 9 | 10 | PreserveNewest 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/NullLoggerTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Xunit; 5 | 6 | namespace Microsoft.Extensions.Logging.Abstractions 7 | { 8 | public class NullLoggerTest 9 | { 10 | [Fact] 11 | public void BeginScope_CanDispose() 12 | { 13 | // Arrange 14 | var logger = NullLogger.Instance; 15 | 16 | // Act & Assert 17 | using (logger.BeginScope("48656c6c6f20576f726c64")) 18 | { 19 | } 20 | } 21 | 22 | [Fact] 23 | public void IsEnabled_AlwaysFalse() 24 | { 25 | // Arrange 26 | var logger = NullLogger.Instance; 27 | 28 | // Act & Assert 29 | Assert.False(logger.IsEnabled(LogLevel.Debug)); 30 | Assert.False(logger.IsEnabled(LogLevel.Trace)); 31 | Assert.False(logger.IsEnabled(LogLevel.Information)); 32 | Assert.False(logger.IsEnabled(LogLevel.Warning)); 33 | Assert.False(logger.IsEnabled(LogLevel.Error)); 34 | Assert.False(logger.IsEnabled(LogLevel.Critical)); 35 | } 36 | 37 | [Fact] 38 | public void Write_Does_Nothing() 39 | { 40 | // Arrange 41 | var logger = NullLogger.Instance; 42 | bool isCalled = false; 43 | 44 | // Act 45 | logger.Log(LogLevel.Trace, eventId: 0, state: null, exception: null, formatter: (ex, message) => { isCalled = true; return string.Empty; }); 46 | 47 | // Assert 48 | Assert.False(isCalled); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/LoggerOfT.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.Abstractions.Internal; 6 | 7 | namespace Microsoft.Extensions.Logging 8 | { 9 | /// 10 | /// Delegates to a new instance using the full name of the given type, created by the 11 | /// provided . 12 | /// 13 | /// The type. 14 | public class Logger : ILogger 15 | { 16 | private readonly ILogger _logger; 17 | 18 | /// 19 | /// Creates a new . 20 | /// 21 | /// The factory. 22 | public Logger(ILoggerFactory factory) 23 | { 24 | if (factory == null) 25 | { 26 | throw new ArgumentNullException(nameof(factory)); 27 | } 28 | 29 | _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T))); 30 | } 31 | 32 | IDisposable ILogger.BeginScope(TState state) 33 | { 34 | return _logger.BeginScope(state); 35 | } 36 | 37 | bool ILogger.IsEnabled(LogLevel logLevel) 38 | { 39 | return _logger.IsEnabled(logLevel); 40 | } 41 | 42 | void ILogger.Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 43 | { 44 | _logger.Log(logLevel, eventId, state, exception, formatter); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/ConsoleLogScope.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Threading; 6 | 7 | namespace Microsoft.Extensions.Logging.Console 8 | { 9 | [Obsolete("Use " + nameof(LoggerExternalScopeProvider) + "instead" )] 10 | public class ConsoleLogScope 11 | { 12 | private readonly string _name; 13 | private readonly object _state; 14 | 15 | internal ConsoleLogScope(string name, object state) 16 | { 17 | _name = name; 18 | _state = state; 19 | } 20 | 21 | public ConsoleLogScope Parent { get; private set; } 22 | 23 | private static AsyncLocal _value = new AsyncLocal(); 24 | public static ConsoleLogScope Current 25 | { 26 | set 27 | { 28 | _value.Value = value; 29 | } 30 | get 31 | { 32 | return _value.Value; 33 | } 34 | } 35 | 36 | public static IDisposable Push(string name, object state) 37 | { 38 | var temp = Current; 39 | Current = new ConsoleLogScope(name, state); 40 | Current.Parent = temp; 41 | 42 | return new DisposableScope(); 43 | } 44 | 45 | public override string ToString() 46 | { 47 | return _state?.ToString(); 48 | } 49 | 50 | private class DisposableScope : IDisposable 51 | { 52 | public void Dispose() 53 | { 54 | Current = Current.Parent; 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/LoggerFilterRule.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// Defines a rule used to filter log messages 10 | /// 11 | public class LoggerFilterRule 12 | { 13 | public LoggerFilterRule(string providerName, string categoryName, LogLevel? logLevel, Func filter) 14 | { 15 | ProviderName = providerName; 16 | CategoryName = categoryName; 17 | LogLevel = logLevel; 18 | Filter = filter; 19 | } 20 | 21 | /// 22 | /// Gets the logger provider type or alias this rule applies to. 23 | /// 24 | public string ProviderName { get; } 25 | 26 | /// 27 | /// Gets the logger category this rule applies to. 28 | /// 29 | public string CategoryName { get; } 30 | 31 | /// 32 | /// Gets the minimum of messages. 33 | /// 34 | public LogLevel? LogLevel { get; } 35 | 36 | /// 37 | /// Gets the filter delegate that would be applied to messages that passed the . 38 | /// 39 | public Func Filter { get; } 40 | 41 | public override string ToString() 42 | { 43 | return $"{nameof(ProviderName)}: '{ProviderName}', {nameof(CategoryName)}: '{CategoryName}', {nameof(LogLevel)}: '{LogLevel}', {nameof(Filter)}: '{Filter}'"; 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.AzureAppServices.Test/WebConfigurationLevelSwitchTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.Logging.AzureAppServices.Internal; 7 | using Xunit; 8 | 9 | namespace Microsoft.Extensions.Logging.AzureAppServices.Test 10 | { 11 | public class WebConfigurationLevelSwitchTests 12 | { 13 | [Theory] 14 | [InlineData("Error", LogLevel.Error)] 15 | [InlineData("Warning", LogLevel.Warning)] 16 | [InlineData("Information", LogLevel.Information)] 17 | [InlineData("Verbose", LogLevel.Trace)] 18 | [InlineData("ABCD", LogLevel.None)] 19 | public void AddsRuleWithCorrectLevel(string levelValue, LogLevel expectedLevel) 20 | { 21 | var configuration = new ConfigurationBuilder().AddInMemoryCollection( 22 | new[] 23 | { 24 | new KeyValuePair("levelKey", levelValue), 25 | }) 26 | .Build(); 27 | 28 | var levelSwitcher = new ConfigurationBasedLevelSwitcher(configuration, typeof(TestFileLoggerProvider), "levelKey"); 29 | 30 | var filterConfiguration = new LoggerFilterOptions(); 31 | levelSwitcher.Configure(filterConfiguration); 32 | 33 | Assert.Equal(1, filterConfiguration.Rules.Count); 34 | 35 | var rule = filterConfiguration.Rules[0]; 36 | Assert.Equal(typeof(TestFileLoggerProvider).FullName, rule.ProviderName); 37 | Assert.Equal(expectedLevel, rule.LogLevel); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Microsoft.Extensions.Logging.Testing.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Helpers for writing tests that use Microsoft.Extensions.Logging. Contains null implementations of the abstractions that do nothing, as well as test implementations that are observable. 5 | netstandard2.0;net461 6 | $(NoWarn);CS1591 7 | $(PackageTags);testing 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/EventIdTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Xunit; 5 | 6 | namespace Microsoft.Extensions.Logging.Test 7 | { 8 | public class EventIdTest 9 | { 10 | [Fact] 11 | public void Equality_operations() 12 | { 13 | Assert.True(new EventId(1).Equals(new EventId(1))); 14 | Assert.True(new EventId(1).Equals((object)new EventId(1))); 15 | Assert.True(new EventId(1).Equals(new EventId(1, "Foo"))); 16 | Assert.True(new EventId(1, "Bar").Equals(new EventId(1, "Foo"))); 17 | 18 | Assert.False(new EventId(1).Equals(new EventId(2))); 19 | Assert.False(new EventId(1).Equals(null)); 20 | Assert.False(new EventId(1, "Foo").Equals(new EventId(2, "Foo"))); 21 | 22 | Assert.True(new EventId(1) == new EventId(1)); 23 | Assert.True(new EventId(1) == new EventId(1, "Foo")); 24 | Assert.True(new EventId(1, "Bar") == new EventId(1, "Foo")); 25 | 26 | Assert.True(new EventId(1) != new EventId(2)); 27 | Assert.True(new EventId(1, "Foo") != new EventId(2, "Foo")); 28 | 29 | Assert.True(new EventId(1).GetHashCode() == new EventId(1).GetHashCode()); 30 | Assert.True(new EventId(1).GetHashCode() == new EventId(1, "Foo").GetHashCode()); 31 | Assert.True(new EventId(1, "Bar").GetHashCode() == new EventId(1, "Foo").GetHashCode()); 32 | 33 | Assert.True(new EventId(1).GetHashCode() != new EventId(2).GetHashCode()); 34 | Assert.True(new EventId(1, "Foo").GetHashCode() != new EventId(2, "Foo").GetHashCode()); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /version.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 3.0.0 4 | alpha1 5 | 6 | 0.3.0 7 | alpha1 8 | 9 | $(VersionPrefix) 10 | $(VersionPrefix)-$(VersionSuffix)-final 11 | $(ExperimentalVersionPrefix)-$(ExperimentalVersionSuffix)-final 12 | t000 13 | a- 14 | $(FeatureBranchVersionPrefix)$(VersionSuffix)-$([System.Text.RegularExpressions.Regex]::Replace('$(FeatureBranchVersionSuffix)', '[^\w-]', '-')) 15 | $(VersionSuffix)-$(BuildNumber) 16 | $(FeatureBranchVersionPrefix)$(ExperimentalVersionSuffix)-$([System.Text.RegularExpressions.Regex]::Replace('$(FeatureBranchVersionSuffix)', '[^\w-]', '-')) 17 | $(ExperimentalVersionSuffix)-$(BuildNumber) 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/LoggerFactoryExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.Abstractions.Internal; 6 | 7 | namespace Microsoft.Extensions.Logging 8 | { 9 | /// 10 | /// ILoggerFactory extension methods for common scenarios. 11 | /// 12 | public static class LoggerFactoryExtensions 13 | { 14 | /// 15 | /// Creates a new ILogger instance using the full name of the given type. 16 | /// 17 | /// The type. 18 | /// The factory. 19 | public static ILogger CreateLogger(this ILoggerFactory factory) 20 | { 21 | if (factory == null) 22 | { 23 | throw new ArgumentNullException(nameof(factory)); 24 | } 25 | return new Logger(factory); 26 | } 27 | /// 28 | /// Creates a new ILogger instance using the full name of the given type. 29 | /// 30 | /// The factory. 31 | /// The type. 32 | public static ILogger CreateLogger(this ILoggerFactory factory, Type type) 33 | { 34 | if (factory == null) 35 | { 36 | throw new ArgumentNullException(nameof(factory)); 37 | } 38 | 39 | if (type == null) 40 | { 41 | throw new ArgumentNullException(nameof(type)); 42 | } 43 | 44 | return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type)); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/ILogger.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | /// 9 | /// Represents a type used to perform logging. 10 | /// 11 | /// Aggregates most logging patterns to a single method. 12 | public interface ILogger 13 | { 14 | /// 15 | /// Writes a log entry. 16 | /// 17 | /// Entry will be written on this level. 18 | /// Id of the event. 19 | /// The entry to be written. Can be also an object. 20 | /// The exception related to this entry. 21 | /// Function to create a string message of the and . 22 | void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter); 23 | 24 | /// 25 | /// Checks if the given is enabled. 26 | /// 27 | /// level to be checked. 28 | /// true if enabled. 29 | bool IsEnabled(LogLevel logLevel); 30 | 31 | /// 32 | /// Begins a logical operation scope. 33 | /// 34 | /// The identifier for the scope. 35 | /// An IDisposable that ends the logical operation scope on dispose. 36 | IDisposable BeginScope(TState state); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /benchmarks/Logging.Performance/LogValuesBenchmarks.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using BenchmarkDotNet.Attributes; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace Microsoft.Extensions.Logging.Performance 9 | { 10 | [AspNetCoreBenchmark] 11 | public class FormattingBenchmarks : LoggingBenchmarkBase 12 | { 13 | private ILogger _logger; 14 | 15 | [Benchmark] 16 | public void TwoArguments() 17 | { 18 | TwoArgumentErrorMessage(_logger, 1, "string", Exception); 19 | } 20 | 21 | [Benchmark(Baseline = true)] 22 | public void NoArguments() 23 | { 24 | NoArgumentErrorMessage(_logger, Exception); 25 | } 26 | 27 | [GlobalSetup] 28 | public void Setup() 29 | { 30 | var services = new ServiceCollection(); 31 | services.AddLogging(); 32 | services.AddSingleton>(); 33 | 34 | _logger = services.BuildServiceProvider().GetService().CreateLogger("Logger"); 35 | } 36 | 37 | public class MessageFormattingLogger: ILogger 38 | { 39 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 40 | { 41 | formatter(state, exception); 42 | } 43 | 44 | public bool IsEnabled(LogLevel logLevel) 45 | { 46 | return true; 47 | } 48 | 49 | public IDisposable BeginScope(TState state) 50 | { 51 | return null; 52 | } 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Configuration/LoggerProviderConfigurationFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Reflection; 7 | using Microsoft.Extensions.Configuration; 8 | 9 | namespace Microsoft.Extensions.Logging.Configuration 10 | { 11 | internal class LoggerProviderConfigurationFactory : ILoggerProviderConfigurationFactory 12 | { 13 | private readonly IEnumerable _configurations; 14 | 15 | public LoggerProviderConfigurationFactory(IEnumerable configurations) 16 | { 17 | _configurations = configurations; 18 | } 19 | 20 | public IConfiguration GetConfiguration(Type providerType) 21 | { 22 | if (providerType == null) 23 | { 24 | throw new ArgumentNullException(nameof(providerType)); 25 | } 26 | 27 | var fullName = providerType.FullName; 28 | var alias = ProviderAliasUtilities.GetAlias(providerType); 29 | var configurationBuilder = new ConfigurationBuilder(); 30 | foreach (var configuration in _configurations) 31 | { 32 | var sectionFromFullName = configuration.Configuration.GetSection(fullName); 33 | configurationBuilder.AddConfiguration(sectionFromFullName); 34 | 35 | if (!string.IsNullOrWhiteSpace(alias)) 36 | { 37 | var sectionFromAlias = configuration.Configuration.GetSection(alias); 38 | configurationBuilder.AddConfiguration(sectionFromAlias); 39 | } 40 | } 41 | return configurationBuilder.Build(); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTestCaseRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Reflection; 7 | using System.Threading; 8 | using Xunit.Abstractions; 9 | using Xunit.Sdk; 10 | 11 | namespace Microsoft.Extensions.Logging.Testing 12 | { 13 | public class LoggedTestCaseRunner : XunitTestCaseRunner 14 | { 15 | public LoggedTestCaseRunner( 16 | IXunitTestCase testCase, 17 | string displayName, 18 | string skipReason, 19 | object[] constructorArguments, 20 | object[] testMethodArguments, 21 | IMessageBus messageBus, 22 | ExceptionAggregator aggregator, 23 | CancellationTokenSource cancellationTokenSource) 24 | : base(testCase, displayName, skipReason, constructorArguments, testMethodArguments, messageBus, aggregator, cancellationTokenSource) 25 | { 26 | } 27 | 28 | protected override XunitTestRunner CreateTestRunner( 29 | ITest test, 30 | IMessageBus messageBus, 31 | Type testClass, 32 | object[] constructorArguments, 33 | MethodInfo testMethod, 34 | object[] testMethodArguments, 35 | string skipReason, 36 | IReadOnlyList beforeAfterAttributes, 37 | ExceptionAggregator aggregator, 38 | CancellationTokenSource cancellationTokenSource) 39 | => new LoggedTestRunner(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, 40 | skipReason, beforeAfterAttributes, new ExceptionAggregator(aggregator), cancellationTokenSource); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedTheoryTestCaseRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Reflection; 7 | using System.Threading; 8 | using Xunit.Abstractions; 9 | using Xunit.Sdk; 10 | 11 | namespace Microsoft.Extensions.Logging.Testing 12 | { 13 | public class LoggedTheoryTestCaseRunner : XunitTheoryTestCaseRunner 14 | { 15 | public LoggedTheoryTestCaseRunner( 16 | IXunitTestCase testCase, 17 | string displayName, 18 | string skipReason, 19 | object[] constructorArguments, 20 | IMessageSink diagnosticMessageSink, 21 | IMessageBus messageBus, 22 | ExceptionAggregator aggregator, 23 | CancellationTokenSource cancellationTokenSource) 24 | : base(testCase, displayName, skipReason, constructorArguments, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource) 25 | { 26 | } 27 | 28 | protected override XunitTestRunner CreateTestRunner( 29 | ITest test, 30 | IMessageBus messageBus, 31 | Type testClass, 32 | object[] constructorArguments, 33 | MethodInfo testMethod, 34 | object[] testMethodArguments, 35 | string skipReason, 36 | IReadOnlyList beforeAfterAttributes, 37 | ExceptionAggregator aggregator, 38 | CancellationTokenSource cancellationTokenSource) 39 | => new LoggedTestRunner(test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, new ExceptionAggregator(aggregator), cancellationTokenSource); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/ConfigurationBasedLevelSwitcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 9 | { 10 | public class ConfigurationBasedLevelSwitcher: IConfigureOptions 11 | { 12 | private readonly IConfiguration _configuration; 13 | private readonly Type _provider; 14 | private readonly string _levelKey; 15 | 16 | public ConfigurationBasedLevelSwitcher(IConfiguration configuration, Type provider, string levelKey) 17 | { 18 | _configuration = configuration; 19 | _provider = provider; 20 | _levelKey = levelKey; 21 | } 22 | 23 | public void Configure(LoggerFilterOptions options) 24 | { 25 | options.Rules.Add(new LoggerFilterRule(_provider.FullName, null, GetLogLevel(), null)); 26 | } 27 | 28 | private LogLevel GetLogLevel() 29 | { 30 | return TextToLogLevel(_configuration.GetSection(_levelKey)?.Value); 31 | } 32 | 33 | private static LogLevel TextToLogLevel(string text) 34 | { 35 | switch (text?.ToUpperInvariant()) 36 | { 37 | case "ERROR": 38 | return LogLevel.Error; 39 | case "WARNING": 40 | return LogLevel.Warning; 41 | case "INFORMATION": 42 | return LogLevel.Information; 43 | case "VERBOSE": 44 | return LogLevel.Trace; 45 | default: 46 | return LogLevel.None; 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/Properties/Resource.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | namespace Microsoft.Extensions.Logging.Abstractions 3 | { 4 | using System.Globalization; 5 | using System.Reflection; 6 | using System.Resources; 7 | 8 | internal static class Resource 9 | { 10 | private static readonly ResourceManager _resourceManager 11 | = new ResourceManager("Microsoft.Extensions.Logging.Abstractions.Resource", typeof(Resource).GetTypeInfo().Assembly); 12 | 13 | /// 14 | /// The format string '{0}' does not have the expected number of named parameters. Expected {1} parameter(s) but found {2} parameter(s). 15 | /// 16 | internal static string UnexpectedNumberOfNamedParameters 17 | { 18 | get { return GetString("UnexpectedNumberOfNamedParameters"); } 19 | } 20 | 21 | /// 22 | /// The format string '{0}' does not have the expected number of named parameters. Expected {1} parameter(s) but found {2} parameter(s). 23 | /// 24 | internal static string FormatUnexpectedNumberOfNamedParameters(object p0, object p1, object p2) 25 | { 26 | return string.Format(CultureInfo.CurrentCulture, GetString("UnexpectedNumberOfNamedParameters"), p0, p1, p2); 27 | } 28 | 29 | private static string GetString(string name, params string[] formatterNames) 30 | { 31 | var value = _resourceManager.GetString(name); 32 | 33 | System.Diagnostics.Debug.Assert(value != null); 34 | 35 | if (formatterNames != null) 36 | { 37 | for (var i = 0; i < formatterNames.Length; i++) 38 | { 39 | value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); 40 | } 41 | } 42 | 43 | return value; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Analyzers/Descriptors.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using Microsoft.CodeAnalysis; 5 | 6 | namespace Microsoft.Extensions.Logging.Analyzers 7 | { 8 | internal class Descriptors 9 | { 10 | public static DiagnosticDescriptor MEL0001NumericsInFormatString = new DiagnosticDescriptor( 11 | "MEL0001", "Numerics should not be used in logging format string", 12 | "Numerics should not be used in logging format string", "Usage", DiagnosticSeverity.Info, true); 13 | 14 | public static DiagnosticDescriptor MEL0002ConcatenationInFormatString = new DiagnosticDescriptor( 15 | "MEL0002", "Logging format string should not be dynamically generated", 16 | "Logging format string should not be dynamically generated", "Usage", DiagnosticSeverity.Info, true); 17 | 18 | public static DiagnosticDescriptor MEL0003FormatParameterCountMismatch = new DiagnosticDescriptor( 19 | "MEL0003", "Logging format string parameter count mismatch", 20 | "Logging format string parameter count mismatch", "Usage", DiagnosticSeverity.Warning, true); 21 | 22 | public static DiagnosticDescriptor MEL0004UseCompiledLogMessages = new DiagnosticDescriptor( 23 | "MEL0004", "Use compiled log messages", 24 | "For improved performance, use pre-compiled log messages instead of calling '{0}' with a string message.", "Performance", DiagnosticSeverity.Info, false); 25 | 26 | public static DiagnosticDescriptor MEL0005UsePascalCasedLogMessageTokens = new DiagnosticDescriptor( 27 | "MEL0005", "Use PascalCase for log message tokens", 28 | "For consistency with logs emitted from other components, use 'PascalCase' for log message tokens.", "Naming", DiagnosticSeverity.Info, false); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/Console/TestConsole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging.Console.Internal; 6 | 7 | namespace Microsoft.Extensions.Logging.Test.Console 8 | { 9 | public class TestConsole : IConsole 10 | { 11 | public static readonly ConsoleColor? DefaultBackgroundColor; 12 | public static readonly ConsoleColor? DefaultForegroundColor; 13 | 14 | private ConsoleSink _sink; 15 | 16 | public TestConsole(ConsoleSink sink) 17 | { 18 | _sink = sink; 19 | BackgroundColor = DefaultBackgroundColor; 20 | ForegroundColor = DefaultForegroundColor; 21 | } 22 | 23 | public ConsoleColor? BackgroundColor { get; private set; } 24 | 25 | public ConsoleColor? ForegroundColor { get; private set; } 26 | 27 | public void Write(string message, ConsoleColor? background, ConsoleColor? foreground) 28 | { 29 | var consoleContext = new ConsoleContext(); 30 | consoleContext.Message = message; 31 | 32 | if (background.HasValue) 33 | { 34 | consoleContext.BackgroundColor = background.Value; 35 | } 36 | 37 | if (foreground.HasValue) 38 | { 39 | consoleContext.ForegroundColor = foreground.Value; 40 | } 41 | 42 | _sink.Write(consoleContext); 43 | 44 | ResetColor(); 45 | } 46 | 47 | public void WriteLine(string message, ConsoleColor? background, ConsoleColor? foreground) 48 | { 49 | Write(message + Environment.NewLine, background, foreground); 50 | } 51 | 52 | public void Flush() 53 | { 54 | } 55 | 56 | private void ResetColor() 57 | { 58 | BackgroundColor = DefaultBackgroundColor; 59 | ForegroundColor = DefaultForegroundColor; 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/LogLevel.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | namespace Microsoft.Extensions.Logging 5 | { 6 | /// 7 | /// Defines logging severity levels. 8 | /// 9 | public enum LogLevel 10 | { 11 | /// 12 | /// Logs that contain the most detailed messages. These messages may contain sensitive application data. 13 | /// These messages are disabled by default and should never be enabled in a production environment. 14 | /// 15 | Trace = 0, 16 | 17 | /// 18 | /// Logs that are used for interactive investigation during development. These logs should primarily contain 19 | /// information useful for debugging and have no long-term value. 20 | /// 21 | Debug = 1, 22 | 23 | /// 24 | /// Logs that track the general flow of the application. These logs should have long-term value. 25 | /// 26 | Information = 2, 27 | 28 | /// 29 | /// Logs that highlight an abnormal or unexpected event in the application flow, but do not otherwise cause the 30 | /// application execution to stop. 31 | /// 32 | Warning = 3, 33 | 34 | /// 35 | /// Logs that highlight when the current flow of execution is stopped due to a failure. These should indicate a 36 | /// failure in the current activity, not an application-wide failure. 37 | /// 38 | Error = 4, 39 | 40 | /// 41 | /// Logs that describe an unrecoverable application or system crash, or a catastrophic failure that requires 42 | /// immediate attention. 43 | /// 44 | Critical = 5, 45 | 46 | /// 47 | /// Not used for writing log messages. Specifies that a logging category should not write any messages. 48 | /// 49 | None = 6, 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Console/Internal/WindowsLogConsole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.IO; 6 | 7 | namespace Microsoft.Extensions.Logging.Console.Internal 8 | { 9 | public class WindowsLogConsole : IConsole 10 | { 11 | private readonly TextWriter _textWriter; 12 | 13 | /// 14 | public WindowsLogConsole(bool stdErr = false) 15 | { 16 | _textWriter = stdErr? System.Console.Error : System.Console.Out; 17 | } 18 | 19 | private bool SetColor(ConsoleColor? background, ConsoleColor? foreground) 20 | { 21 | if (background.HasValue) 22 | { 23 | System.Console.BackgroundColor = background.Value; 24 | } 25 | 26 | if (foreground.HasValue) 27 | { 28 | System.Console.ForegroundColor = foreground.Value; 29 | } 30 | 31 | return background.HasValue || foreground.HasValue; 32 | } 33 | 34 | private void ResetColor() 35 | { 36 | System.Console.ResetColor(); 37 | } 38 | 39 | public void Write(string message, ConsoleColor? background, ConsoleColor? foreground) 40 | { 41 | var colorChanged = SetColor(background, foreground); 42 | _textWriter.Write(message); 43 | if (colorChanged) 44 | { 45 | ResetColor(); 46 | } 47 | } 48 | 49 | public void WriteLine(string message, ConsoleColor? background, ConsoleColor? foreground) 50 | { 51 | var colorChanged = SetColor(background, foreground); 52 | _textWriter.WriteLine(message); 53 | if (colorChanged) 54 | { 55 | ResetColor(); 56 | } 57 | } 58 | 59 | public void Flush() 60 | { 61 | // No action required as for every write, data is sent directly to the console 62 | // output stream 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/XunitLoggerFactoryExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Logging.Testing; 7 | using Xunit.Abstractions; 8 | 9 | namespace Microsoft.Extensions.Logging 10 | { 11 | public static class XunitLoggerFactoryExtensions 12 | { 13 | public static ILoggingBuilder AddXunit(this ILoggingBuilder builder, ITestOutputHelper output) 14 | { 15 | builder.Services.AddSingleton(new XunitLoggerProvider(output)); 16 | return builder; 17 | } 18 | 19 | public static ILoggingBuilder AddXunit(this ILoggingBuilder builder, ITestOutputHelper output, LogLevel minLevel) 20 | { 21 | builder.Services.AddSingleton(new XunitLoggerProvider(output, minLevel)); 22 | return builder; 23 | } 24 | 25 | public static ILoggingBuilder AddXunit(this ILoggingBuilder builder, ITestOutputHelper output, LogLevel minLevel, DateTimeOffset? logStart) 26 | { 27 | builder.Services.AddSingleton(new XunitLoggerProvider(output, minLevel, logStart)); 28 | return builder; 29 | } 30 | 31 | public static ILoggerFactory AddXunit(this ILoggerFactory loggerFactory, ITestOutputHelper output) 32 | { 33 | loggerFactory.AddProvider(new XunitLoggerProvider(output)); 34 | return loggerFactory; 35 | } 36 | 37 | public static ILoggerFactory AddXunit(this ILoggerFactory loggerFactory, ITestOutputHelper output, LogLevel minLevel) 38 | { 39 | loggerFactory.AddProvider(new XunitLoggerProvider(output, minLevel)); 40 | return loggerFactory; 41 | } 42 | 43 | public static ILoggerFactory AddXunit(this ILoggerFactory loggerFactory, ITestOutputHelper output, LogLevel minLevel, DateTimeOffset? logStart) 44 | { 45 | loggerFactory.AddProvider(new XunitLoggerProvider(output, minLevel, logStart)); 46 | return loggerFactory; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.EventSource/EventSourceLoggerFactoryExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.DependencyInjection.Extensions; 7 | using Microsoft.Extensions.Logging.EventSource; 8 | using Microsoft.Extensions.Options; 9 | 10 | namespace Microsoft.Extensions.Logging 11 | { 12 | /// 13 | /// Extension methods for the class. 14 | /// 15 | public static class EventSourceLoggerFactoryExtensions 16 | { 17 | /// 18 | /// Adds an event logger named 'EventSource' to the factory. 19 | /// 20 | /// The extension method argument. 21 | public static ILoggingBuilder AddEventSourceLogger(this ILoggingBuilder builder) 22 | { 23 | if (builder == null) 24 | { 25 | throw new ArgumentNullException(nameof(builder)); 26 | } 27 | 28 | builder.Services.TryAddSingleton(LoggingEventSource.Instance); 29 | builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); 30 | builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, EventLogFiltersConfigureOptions>()); 31 | builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, EventLogFiltersConfigureOptionsChangeSource>()); 32 | return builder; 33 | } 34 | 35 | /// 36 | /// Adds an event logger that is enabled for .Information or higher. 37 | /// 38 | /// The extension method argument. 39 | public static ILoggerFactory AddEventSourceLogger(this ILoggerFactory factory) 40 | { 41 | if (factory == null) 42 | { 43 | throw new ArgumentNullException(nameof(factory)); 44 | } 45 | 46 | factory.AddProvider(new EventSourceLoggerProvider(LoggingEventSource.Instance, handleFilters: true)); 47 | 48 | return factory; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/TestLogger.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging.Testing 7 | { 8 | public class TestLogger : ILogger 9 | { 10 | private object _scope; 11 | private readonly ITestSink _sink; 12 | private readonly string _name; 13 | private readonly Func _filter; 14 | 15 | public TestLogger(string name, ITestSink sink, bool enabled) 16 | : this(name, sink, _ => enabled) 17 | { 18 | } 19 | 20 | public TestLogger(string name, ITestSink sink, Func filter) 21 | { 22 | _sink = sink; 23 | _name = name; 24 | _filter = filter; 25 | } 26 | 27 | public string Name { get; set; } 28 | 29 | public IDisposable BeginScope(TState state) 30 | { 31 | _scope = state; 32 | 33 | _sink.Begin(new BeginScopeContext() 34 | { 35 | LoggerName = _name, 36 | Scope = state, 37 | }); 38 | 39 | return TestDisposable.Instance; 40 | } 41 | 42 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 43 | { 44 | if (!IsEnabled(logLevel)) 45 | { 46 | return; 47 | } 48 | 49 | _sink.Write(new WriteContext() 50 | { 51 | LogLevel = logLevel, 52 | EventId = eventId, 53 | State = state, 54 | Exception = exception, 55 | Formatter = (s, e) => formatter((TState)s, e), 56 | LoggerName = _name, 57 | Scope = _scope 58 | }); 59 | } 60 | 61 | public bool IsEnabled(LogLevel logLevel) 62 | { 63 | return logLevel != LogLevel.None && _filter(logLevel); 64 | } 65 | 66 | private class TestDisposable : IDisposable 67 | { 68 | public static readonly TestDisposable Instance = new TestDisposable(); 69 | 70 | public void Dispose() 71 | { 72 | // intentionally does nothing 73 | } 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/TestSink.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Concurrent; 6 | 7 | namespace Microsoft.Extensions.Logging.Testing 8 | { 9 | public class TestSink : ITestSink 10 | { 11 | private ConcurrentQueue _scopes; 12 | private ConcurrentQueue _writes; 13 | 14 | public TestSink( 15 | Func writeEnabled = null, 16 | Func beginEnabled = null) 17 | { 18 | WriteEnabled = writeEnabled; 19 | BeginEnabled = beginEnabled; 20 | 21 | _scopes = new ConcurrentQueue(); 22 | _writes = new ConcurrentQueue(); 23 | } 24 | 25 | public Func WriteEnabled { get; set; } 26 | 27 | public Func BeginEnabled { get; set; } 28 | 29 | public IProducerConsumerCollection Scopes { get => _scopes; set => _scopes = new ConcurrentQueue(value); } 30 | 31 | public IProducerConsumerCollection Writes { get => _writes; set => _writes = new ConcurrentQueue(value); } 32 | 33 | public event Action MessageLogged; 34 | 35 | public event Action ScopeStarted; 36 | 37 | public void Write(WriteContext context) 38 | { 39 | if (WriteEnabled == null || WriteEnabled(context)) 40 | { 41 | _writes.Enqueue(context); 42 | } 43 | MessageLogged?.Invoke(context); 44 | } 45 | 46 | public void Begin(BeginScopeContext context) 47 | { 48 | if (BeginEnabled == null || BeginEnabled(context)) 49 | { 50 | _scopes.Enqueue(context); 51 | } 52 | ScopeStarted?.Invoke(context); 53 | } 54 | 55 | public static bool EnableWithTypeName(WriteContext context) 56 | { 57 | return context.LoggerName.Equals(typeof(T).FullName); 58 | } 59 | 60 | public static bool EnableWithTypeName(BeginScopeContext context) 61 | { 62 | return context.LoggerName.Equals(typeof(T).FullName); 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/TraceSourceLoggerProviderTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | #if NET461 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Diagnostics; 8 | using Microsoft.Extensions.Logging.TraceSource; 9 | using Xunit; 10 | 11 | namespace Microsoft.Extensions.Logging.Test 12 | { 13 | public class TraceSourceLoggerProviderTest 14 | { 15 | [Fact] 16 | public void Dispose_TraceListenerIsFlushedOnce() 17 | { 18 | // Arrange 19 | var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test"); 20 | testSwitch.Level = SourceLevels.Warning; 21 | var listener = new BufferedConsoleTraceListener(); 22 | 23 | TraceSourceLoggerProvider provider = new TraceSourceLoggerProvider(testSwitch, listener); 24 | var logger1 = provider.CreateLogger("FirstLogger"); 25 | var logger2 = provider.CreateLogger("SecondLogger"); 26 | logger1.LogError("message1"); 27 | logger2.LogError("message2"); 28 | 29 | // Act 30 | provider.Dispose(); 31 | 32 | // Assert 33 | Assert.Equal(1, listener.FlushCount); 34 | Assert.Equal(new [] 35 | { 36 | "FirstLogger Error: 0 : ", 37 | "message1" + Environment.NewLine, 38 | "SecondLogger Error: 0 : ", 39 | "message2" + Environment.NewLine 40 | }, listener.Messages); 41 | } 42 | 43 | private class BufferedConsoleTraceListener : TraceListener 44 | { 45 | public int FlushCount { get; set; } 46 | public List Messages { get; } = new List(); 47 | 48 | public override void Flush() 49 | { 50 | FlushCount++; 51 | } 52 | 53 | public override void Write(string message) 54 | { 55 | Messages.Add(message); 56 | } 57 | 58 | public override void WriteLine(string message) 59 | { 60 | Messages.Add(message + Environment.NewLine); 61 | } 62 | } 63 | } 64 | } 65 | #elif NETCOREAPP2_2 66 | #else 67 | #error Target framework needs to be updated 68 | #endif 69 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/LoggingServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.Logging; 6 | using Microsoft.Extensions.DependencyInjection.Extensions; 7 | using Microsoft.Extensions.Options; 8 | 9 | namespace Microsoft.Extensions.DependencyInjection 10 | { 11 | /// 12 | /// Extension methods for setting up logging services in an . 13 | /// 14 | public static class LoggingServiceCollectionExtensions 15 | { 16 | /// 17 | /// Adds logging services to the specified . 18 | /// 19 | /// The to add services to. 20 | /// The so that additional calls can be chained. 21 | public static IServiceCollection AddLogging(this IServiceCollection services) 22 | { 23 | return AddLogging(services, builder => { }); 24 | } 25 | 26 | /// 27 | /// Adds logging services to the specified . 28 | /// 29 | /// The to add services to. 30 | /// The configuration delegate. 31 | /// The so that additional calls can be chained. 32 | public static IServiceCollection AddLogging(this IServiceCollection services, Action configure) 33 | { 34 | if (services == null) 35 | { 36 | throw new ArgumentNullException(nameof(services)); 37 | } 38 | 39 | services.AddOptions(); 40 | 41 | services.TryAdd(ServiceDescriptor.Singleton()); 42 | services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>))); 43 | 44 | services.TryAddEnumerable(ServiceDescriptor.Singleton>( 45 | new DefaultLoggerLevelConfigureOptions(LogLevel.Information))); 46 | 47 | configure(new LoggingBuilder(services)); 48 | return services; 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Testing/Xunit/LoggedConditionalTheoryDiscoverer.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Collections.Generic; 5 | using Microsoft.AspNetCore.Testing.xunit; 6 | using Xunit.Abstractions; 7 | using Xunit.Sdk; 8 | 9 | namespace Microsoft.Extensions.Logging.Testing 10 | { 11 | public class LoggedConditionalTheoryDiscoverer : LoggedTheoryDiscoverer 12 | { 13 | public LoggedConditionalTheoryDiscoverer(IMessageSink diagnosticMessageSink) 14 | : base(diagnosticMessageSink) 15 | { 16 | } 17 | 18 | protected override IEnumerable CreateTestCasesForTheory( 19 | ITestFrameworkDiscoveryOptions discoveryOptions, 20 | ITestMethod testMethod, 21 | IAttributeInfo theoryAttribute) 22 | { 23 | var skipReason = testMethod.EvaluateSkipConditions(); 24 | return skipReason != null 25 | ? new[] { new SkippedTestCase(skipReason, DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod) } 26 | : base.CreateTestCasesForTheory(discoveryOptions, testMethod, theoryAttribute); 27 | } 28 | 29 | protected override IEnumerable CreateTestCasesForDataRow( 30 | ITestFrameworkDiscoveryOptions discoveryOptions, 31 | ITestMethod testMethod, IAttributeInfo theoryAttribute, 32 | object[] dataRow) 33 | { 34 | var skipReason = testMethod.EvaluateSkipConditions(); 35 | if (skipReason == null && dataRow?.Length > 0) 36 | { 37 | var obj = dataRow[0]; 38 | if (obj != null) 39 | { 40 | var type = obj.GetType(); 41 | var property = type.GetProperty("Skip"); 42 | if (property != null && property.PropertyType.Equals(typeof(string))) 43 | { 44 | skipReason = property.GetValue(obj) as string; 45 | } 46 | } 47 | } 48 | 49 | return skipReason != null 50 | ? base.CreateTestCasesForSkippedDataRow(discoveryOptions, testMethod, theoryAttribute, dataRow, skipReason) 51 | : base.CreateTestCasesForDataRow(discoveryOptions, testMethod, theoryAttribute, dataRow); 52 | } 53 | 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Abstractions/LoggerExternalScopeProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Runtime.InteropServices; 8 | using System.Threading; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace Microsoft.Extensions.Logging 12 | { 13 | /// 14 | /// Default implemenation of 15 | /// 16 | public class LoggerExternalScopeProvider : IExternalScopeProvider 17 | { 18 | private readonly AsyncLocal _currentScope = new AsyncLocal(); 19 | 20 | /// 21 | public void ForEachScope(Action callback, TState state) 22 | { 23 | void Report(Scope current) 24 | { 25 | if (current == null) 26 | { 27 | return; 28 | } 29 | Report(current.Parent); 30 | callback(current.State, state); 31 | } 32 | Report(_currentScope.Value); 33 | } 34 | 35 | /// 36 | public IDisposable Push(object state) 37 | { 38 | var parent = _currentScope.Value; 39 | var newScope = new Scope(this, state, parent); 40 | _currentScope.Value = newScope; 41 | 42 | return newScope; 43 | } 44 | 45 | private class Scope : IDisposable 46 | { 47 | private readonly LoggerExternalScopeProvider _provider; 48 | private bool _isDisposed; 49 | 50 | internal Scope(LoggerExternalScopeProvider provider, object state, Scope parent) 51 | { 52 | _provider = provider; 53 | State = state; 54 | Parent = parent; 55 | } 56 | 57 | public Scope Parent { get; } 58 | 59 | public object State { get; } 60 | 61 | public override string ToString() 62 | { 63 | return State?.ToString(); 64 | } 65 | 66 | public void Dispose() 67 | { 68 | if (!_isDisposed) 69 | { 70 | _provider._currentScope.Value = Parent; 71 | _isDisposed = true; 72 | } 73 | } 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /test/Microsoft.Extensions.Logging.Test/TraceSourceLoggerTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System.Diagnostics; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Xunit; 7 | 8 | namespace Microsoft.Extensions.Logging.Test 9 | { 10 | public class TraceSourceLoggerTest 11 | { 12 | [Fact] 13 | public static void IsEnabledReturnsCorrectValue() 14 | { 15 | // Arrange 16 | var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test"); 17 | testSwitch.Level = SourceLevels.Warning; 18 | 19 | var factory = TestLoggerBuilder.Create(builder => builder.AddTraceSource(testSwitch)); 20 | 21 | // Act 22 | var logger = factory.CreateLogger("Test"); 23 | 24 | // Assert 25 | Assert.False(logger.IsEnabled(LogLevel.None)); 26 | Assert.True(logger.IsEnabled(LogLevel.Critical)); 27 | Assert.True(logger.IsEnabled(LogLevel.Error)); 28 | Assert.True(logger.IsEnabled(LogLevel.Warning)); 29 | Assert.False(logger.IsEnabled(LogLevel.Information)); 30 | Assert.False(logger.IsEnabled(LogLevel.Debug)); 31 | Assert.False(logger.IsEnabled(LogLevel.Trace)); 32 | } 33 | 34 | [Theory] 35 | [InlineData(SourceLevels.Warning, SourceLevels.Information, true)] 36 | [InlineData(SourceLevels.Information, SourceLevels.Information, true)] 37 | [InlineData(SourceLevels.Information, SourceLevels.Warning, true)] 38 | [InlineData(SourceLevels.Warning, SourceLevels.Warning, false)] 39 | public static void MultipleLoggers_IsEnabledReturnsCorrectValue(SourceLevels first, SourceLevels second, bool expected) 40 | { 41 | // Arrange 42 | var firstSwitch = new SourceSwitch("FirstSwitch", "First Test Switch"); 43 | firstSwitch.Level = first; 44 | 45 | var secondSwitch = new SourceSwitch("SecondSwitch", "Second Test Switch"); 46 | secondSwitch.Level = second; 47 | 48 | // Act 49 | 50 | var factory = TestLoggerBuilder.Create(builder => builder 51 | .AddTraceSource(firstSwitch) 52 | .AddTraceSource(secondSwitch)); 53 | 54 | var logger = factory.CreateLogger("Test"); 55 | 56 | // Assert 57 | Assert.Equal(expected, logger.IsEnabled(LogLevel.Information)); 58 | } 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.Debug/DebugLoggerFactoryExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.DependencyInjection.Extensions; 7 | using Microsoft.Extensions.Logging.Debug; 8 | 9 | namespace Microsoft.Extensions.Logging 10 | { 11 | /// 12 | /// Extension methods for the class. 13 | /// 14 | public static class DebugLoggerFactoryExtensions 15 | { 16 | /// 17 | /// Adds a debug logger named 'Debug' to the factory. 18 | /// 19 | /// The extension method argument. 20 | public static ILoggingBuilder AddDebug(this ILoggingBuilder builder) 21 | { 22 | builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); 23 | 24 | return builder; 25 | } 26 | 27 | /// 28 | /// Adds a debug logger that is enabled for .Information or higher. 29 | /// 30 | /// The extension method argument. 31 | public static ILoggerFactory AddDebug(this ILoggerFactory factory) 32 | { 33 | return AddDebug(factory, LogLevel.Information); 34 | } 35 | 36 | /// 37 | /// Adds a debug logger that is enabled as defined by the filter function. 38 | /// 39 | /// The extension method argument. 40 | /// The function used to filter events based on the log level. 41 | public static ILoggerFactory AddDebug(this ILoggerFactory factory, Func filter) 42 | { 43 | factory.AddProvider(new DebugLoggerProvider(filter)); 44 | return factory; 45 | } 46 | 47 | /// 48 | /// Adds a debug logger that is enabled for s of minLevel or higher. 49 | /// 50 | /// The extension method argument. 51 | /// The minimum to be logged 52 | public static ILoggerFactory AddDebug(this ILoggerFactory factory, LogLevel minLevel) 53 | { 54 | return AddDebug( 55 | factory, 56 | (_, logLevel) => logLevel >= minLevel); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging.AzureAppServices/Internal/BatchingLogger.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | using System.Text; 6 | 7 | namespace Microsoft.Extensions.Logging.AzureAppServices.Internal 8 | { 9 | public class BatchingLogger : ILogger 10 | { 11 | private readonly BatchingLoggerProvider _provider; 12 | private readonly string _category; 13 | 14 | public BatchingLogger(BatchingLoggerProvider loggerProvider, string categoryName) 15 | { 16 | _provider = loggerProvider; 17 | _category = categoryName; 18 | } 19 | 20 | public IDisposable BeginScope(TState state) 21 | { 22 | return null; 23 | } 24 | 25 | public bool IsEnabled(LogLevel logLevel) 26 | { 27 | return _provider.IsEnabled; 28 | } 29 | 30 | public void Log(DateTimeOffset timestamp, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 31 | { 32 | if (!IsEnabled(logLevel)) 33 | { 34 | return; 35 | } 36 | 37 | var builder = new StringBuilder(); 38 | builder.Append(timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff zzz")); 39 | builder.Append(" ["); 40 | builder.Append(logLevel.ToString()); 41 | builder.Append("] "); 42 | builder.Append(_category); 43 | 44 | var scopeProvider = _provider.ScopeProvider; 45 | if (scopeProvider != null) 46 | { 47 | scopeProvider.ForEachScope((scope, stringBuilder) => 48 | { 49 | stringBuilder.Append(" => ").Append(scope); 50 | }, builder); 51 | 52 | builder.AppendLine(":"); 53 | } 54 | else 55 | { 56 | builder.Append(": "); 57 | } 58 | 59 | builder.AppendLine(formatter(state, exception)); 60 | 61 | if (exception != null) 62 | { 63 | builder.AppendLine(exception.ToString()); 64 | } 65 | 66 | _provider.AddMessage(timestamp, builder.ToString()); 67 | } 68 | 69 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 70 | { 71 | Log(DateTimeOffset.Now, logLevel, eventId, state, exception, formatter); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/Microsoft.Extensions.Logging/LoggerInformation.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) .NET Foundation. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 3 | 4 | using System; 5 | 6 | namespace Microsoft.Extensions.Logging 7 | { 8 | internal readonly struct MessageLogger 9 | { 10 | public MessageLogger(ILogger logger, string category, Type providerType, LogLevel? minLevel, Func filter) 11 | { 12 | Logger = logger; 13 | Category = category; 14 | ProviderType = providerType; 15 | MinLevel = minLevel; 16 | Filter = filter; 17 | } 18 | 19 | public ILogger Logger { get; } 20 | 21 | public string Category { get; } 22 | 23 | public Type ProviderType { get; } 24 | 25 | public LogLevel? MinLevel { get; } 26 | 27 | public Func Filter { get; } 28 | 29 | public bool IsEnabled(LogLevel level) 30 | { 31 | if (MinLevel != null && level < MinLevel) 32 | { 33 | return false; 34 | } 35 | 36 | if (Filter != null) 37 | { 38 | return Filter(ProviderType.FullName, Category, level); 39 | } 40 | 41 | return true; 42 | } 43 | } 44 | 45 | internal readonly struct ScopeLogger 46 | { 47 | public ScopeLogger(ILogger logger, IExternalScopeProvider externalScopeProvider) 48 | { 49 | Logger = logger; 50 | ExternalScopeProvider = externalScopeProvider; 51 | } 52 | 53 | public ILogger Logger { get; } 54 | 55 | public IExternalScopeProvider ExternalScopeProvider { get; } 56 | 57 | public IDisposable CreateScope(TState state) 58 | { 59 | if (ExternalScopeProvider != null) 60 | { 61 | return ExternalScopeProvider.Push(state); 62 | } 63 | return Logger.BeginScope(state); 64 | } 65 | } 66 | 67 | internal readonly struct LoggerInformation 68 | { 69 | public LoggerInformation(ILoggerProvider provider, string category) : this() 70 | { 71 | ProviderType = provider.GetType(); 72 | Logger = provider.CreateLogger(category); 73 | Category = category; 74 | ExternalScope = provider is ISupportExternalScope; 75 | } 76 | 77 | public ILogger Logger { get; } 78 | 79 | public string Category { get; } 80 | 81 | public Type ProviderType { get; } 82 | 83 | public bool ExternalScope { get; } 84 | } 85 | } --------------------------------------------------------------------------------