-
Notifications
You must be signed in to change notification settings - Fork 469
Add keyed ILogger which forwards to ScriptHost when possible #11398
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jviau
wants to merge
7
commits into
dev
Choose a base branch
from
u/jviau/log-forwarder
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
46b1a61
Add keyed ILogger which forwards to ScriptHost when possible
jviau da519b6
Suppress warning in test
jviau 9d5193b
Add caching to ForwardingLoggerFactory
jviau 9e44e5f
Skip copying ILoggerFactory
jviau 2360d3e
Update release_notes.md
jviau 065fbc2
Rearrange some serivce setup. Fix tests
jviau a285a71
Move dependency setup back to AddTelemetryPublisher
jviau File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
8 changes: 6 additions & 2 deletions
8
src/WebJobs.Script.WebHost/Diagnostics/ILoggingBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,23 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the MIT License. See License.txt in the project root for license information. | ||
|
||
using Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
#nullable enable | ||
|
||
namespace Microsoft.Extensions.Logging | ||
{ | ||
public static class ILoggingBuilderExtensions | ||
{ | ||
public static void AddWebJobsSystem<T>(this ILoggingBuilder builder) where T : SystemLoggerProvider | ||
public static ILoggingBuilder AddWebJobsSystem<T>(this ILoggingBuilder builder) | ||
where T : SystemLoggerProvider | ||
{ | ||
builder.Services.AddSingleton<ILoggerProvider, T>(); | ||
|
||
// Log all logs to SystemLogger | ||
builder.AddDefaultWebJobsFilters<T>(LogLevel.Trace); | ||
return builder; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the MIT License. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using System.Diagnostics; | ||
using System.Diagnostics.CodeAnalysis; | ||
using Microsoft.Azure.WebJobs.Script; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
#nullable enable | ||
|
||
namespace Microsoft.Extensions.Logging | ||
{ | ||
internal class ForwardingLogger : ILogger | ||
{ | ||
// The service key to use for dependency injection to get forwarding loggers. | ||
public const string ServiceKey = "Forwarding"; | ||
|
||
private readonly string _categoryName; | ||
private readonly ILogger _fallback; | ||
private readonly IScriptHostManager _manager; | ||
|
||
// We use weak references so as to not keep a ScriptHost alive after it shuts down. | ||
private readonly WeakReference<ILogger> _current = new(null!); | ||
private readonly WeakReference<IServiceProvider> _services = new(null!); | ||
|
||
public ForwardingLogger(string categoryName, ILogger inner, IScriptHostManager manager) | ||
{ | ||
ArgumentNullException.ThrowIfNull(inner); | ||
ArgumentNullException.ThrowIfNull(manager); | ||
_categoryName = categoryName; | ||
_fallback = inner; | ||
_manager = manager; | ||
} | ||
|
||
private ILogger Current | ||
{ | ||
get | ||
{ | ||
if (TryGetCurrentLogger(out ILogger? logger)) | ||
{ | ||
return logger; | ||
} | ||
|
||
// No current ScriptHost logger, or the ScriptHost is gone. Use the fallback WebHost logger. | ||
return _fallback; | ||
} | ||
} | ||
|
||
public IDisposable? BeginScope<TState>(TState state) | ||
where TState : notnull | ||
=> Current.BeginScope(state); | ||
|
||
public bool IsEnabled(LogLevel logLevel) => Current.IsEnabled(logLevel); | ||
|
||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) | ||
=> Current.Log(logLevel, eventId, state, exception, formatter); | ||
|
||
private bool TryGetCurrentLogger([NotNullWhen(true)] out ILogger? logger) | ||
{ | ||
if (IsLoggerCurrent(out logger)) | ||
{ | ||
return true; | ||
} | ||
else if (_manager.Services is { } services) | ||
{ | ||
logger = services.GetRequiredService<ILoggerFactory>().CreateLogger(_categoryName); | ||
_services.SetTarget(services); | ||
_current.SetTarget(logger); | ||
return true; | ||
} | ||
|
||
logger = null; | ||
return false; | ||
} | ||
|
||
private bool IsLoggerCurrent([NotNullWhen(true)] out ILogger? logger) | ||
{ | ||
// First check if the last IServiceProvider we used is still active. | ||
if (_services.TryGetTarget(out IServiceProvider? services) | ||
&& ReferenceEquals(services, _manager.Services)) | ||
{ | ||
// Service provider is still correct, so our logger is current. | ||
return _current.TryGetTarget(out logger); | ||
} | ||
|
||
logger = null; | ||
return false; | ||
} | ||
} | ||
|
||
[DebuggerDisplay("{_logger}")] | ||
internal class ForwardingLogger<T> : ILogger<T> | ||
{ | ||
private readonly ILogger _logger; | ||
|
||
public ForwardingLogger([ForwardingLogger] ILoggerFactory factory) | ||
{ | ||
ArgumentNullException.ThrowIfNull(factory); | ||
_logger = factory.CreateLogger<T>(); | ||
} | ||
|
||
IDisposable? ILogger.BeginScope<TState>(TState state) => _logger.BeginScope(state); | ||
|
||
bool ILogger.IsEnabled(LogLevel logLevel) => _logger.IsEnabled(logLevel); | ||
|
||
void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) => | ||
_logger.Log(logLevel, eventId, state, exception, formatter); | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
src/WebJobs.Script/Diagnostics/ForwardingLoggerAttribute.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the MIT License. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Microsoft.Extensions.Logging | ||
{ | ||
[AttributeUsage(AttributeTargets.Parameter)] | ||
internal class ForwardingLoggerAttribute() | ||
: FromKeyedServicesAttribute(ForwardingLogger.ServiceKey) | ||
{ | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the MIT License. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using System.Diagnostics; | ||
using Microsoft.Azure.WebJobs.Script; | ||
|
||
#nullable enable | ||
|
||
namespace Microsoft.Extensions.Logging | ||
{ | ||
/// <summary> | ||
/// A logger factory that creates loggers which track the current active ScriptHost (if any), falling | ||
/// back to the WebHost logger if no ScriptHost is active. | ||
/// </summary> | ||
[DebuggerDisplay(@"InnerFactory = \{ {_inner} \}, ScriptHostState = {_manager.State}")] | ||
public sealed class ForwardingLoggerFactory : ILoggerFactory | ||
{ | ||
private readonly ILoggerFactory _inner; | ||
private readonly IScriptHostManager _manager; | ||
|
||
public ForwardingLoggerFactory(ILoggerFactory inner, IScriptHostManager manager) | ||
{ | ||
ArgumentNullException.ThrowIfNull(inner); | ||
ArgumentNullException.ThrowIfNull(manager); | ||
_inner = inner; | ||
_manager = manager; | ||
} | ||
|
||
/// <inheritdoc /> | ||
public void AddProvider(ILoggerProvider provider) | ||
=> throw new NotSupportedException( | ||
$"{nameof(ILoggerProvider)} can not be added to the {nameof(ForwardingLoggerFactory)}."); | ||
|
||
/// <inheritdoc /> | ||
public ILogger CreateLogger(string categoryName) | ||
=> new ForwardingLogger(categoryName, _inner.CreateLogger(categoryName), _manager); | ||
|
||
/// <inheritdoc /> | ||
public void Dispose() | ||
{ | ||
// no op. | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
test/WebJobs.Script.Tests/Diagnostics/ForwardingLoggerAttributeTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the MIT License. See License.txt in the project root for license information. | ||
|
||
using AwesomeAssertions; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
using Xunit; | ||
|
||
namespace Microsoft.Azure.WebJobs.Script.Tests.Diagnostics | ||
{ | ||
public class ForwardingLoggerAttributeTests | ||
{ | ||
[Fact] | ||
public void Key_IsCorrect() | ||
{ | ||
ForwardingLoggerAttribute attribute = new(); | ||
|
||
attribute.Key.Should().BeOfType<string>() | ||
.Which.Should().NotBeNullOrWhiteSpace() | ||
.And.Be(ForwardingLogger.ServiceKey); | ||
} | ||
|
||
[Fact] | ||
public void Import_GetsService() | ||
{ | ||
object nonKeyed = new(); | ||
object keyed = new(); | ||
|
||
ServiceCollection services = new(); | ||
services.AddSingleton(nonKeyed); | ||
services.AddKeyedSingleton(ForwardingLogger.ServiceKey, keyed); | ||
services.AddSingleton<TestClass>(); | ||
|
||
TestClass test = services.BuildServiceProvider().GetRequiredService<TestClass>(); | ||
|
||
test.Instance.Should().BeSameAs(keyed); | ||
} | ||
|
||
private class TestClass([ForwardingLogger] object instance) | ||
{ | ||
public object Instance => instance; | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have found a couple times recently that having access to
IServiceProvider
here is useful. Not sure if there is a reason we didn't expose it in the past?