Skip to content

Commit

Permalink
Merge pull request #144 from Lombiq/issue/NEST-501
Browse files Browse the repository at this point in the history
NEST-501:  Writing debug messages to the Debug output and not the log files
  • Loading branch information
wAsnk authored Jul 18, 2024
2 parents ad9e41c + 4c1aff6 commit bdf7fc7
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 25 deletions.
4 changes: 2 additions & 2 deletions Lombiq.TrainingDemo.Tests/Lombiq.TrainingDemo.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
<PackageReference Include="Moq" Version="4.20.69" />
<PackageReference Include="Moq.AutoMock" Version="3.5.0" />
<PackageReference Include="Shouldly" Version="4.2.1" />
<PackageReference Include="xunit" Version="2.8.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.0">
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
19 changes: 8 additions & 11 deletions Lombiq.TrainingDemo/Middlewares/RequestLoggingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
* in any ASP.NET Core app but nevertheless, let's see a simple example, though a bit spiced up with Orchard services.
* For more info on middlewares in general check out
* https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/. Check out this tutorial too:
* https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write
* https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write.
*/

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using OrchardCore.Settings;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Lombiq.TrainingDemo.Middlewares;
Expand All @@ -28,12 +28,11 @@ public class RequestLoggingMiddleware
// You need to inject a RequestDelegate instance here.
public RequestLoggingMiddleware(RequestDelegate next) => _next = next;

// This method is the actual middleware. Note that apart from the first parameter obligatorily being HttpContext
// This method is the actual middleware. Note that apart from the first parameter obligatorily being HttpContext,
// further parameters can be injected Orchard services.
public async Task InvokeAsync(
HttpContext context,
ISiteService siteService,
ILogger<RequestLoggingMiddleware> logger)
ISiteService siteService)
{
// We let the next middleware run, but this is not mandatory: if this middleware would return a cached page for
// example then we would write the cached response to the HttpContext and leave this out.
Expand All @@ -42,12 +41,10 @@ public async Task InvokeAsync(
// middleware that would normally result in a 404 or an 503, so it's maybe better to always let them bubble up.
// But keep in mind that any uncaught exception here in your code will result in an error page.

// We use LogError() not because we're logging an error just so the message shows up in the log even with log
// levels ignoring e.g. info or debug entries. Use the logging methods appropriately otherwise!
logger.LogError(
"Expected non-error - The url {Url} was just hit on the site {Name}.",
UriHelper.GetDisplayUrl(context.Request),
(await siteService.GetSiteSettingsAsync()).SiteName);
// Writing a message to the debug output, just so we can see this code running. This will be visible in output
// window of your IDE when running the app with the debugger attached.
Debug.WriteLine(
$"The url {UriHelper.GetDisplayUrl(context.Request)} was just hit on the site {(await siteService.GetSiteSettingsAsync()).SiteName}.");
}
}

Expand Down
18 changes: 6 additions & 12 deletions Lombiq.TrainingDemo/Services/DemoBackgroundTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
*/

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OrchardCore.BackgroundTasks;
using OrchardCore.BackgroundTasks.Services;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -32,28 +32,22 @@ public class DemoBackgroundTask : IBackgroundTask
// Setting a maximum time this background task will be executed.
private const int MaxCount = 5;

private readonly ILogger<DemoBackgroundTask> _logger;

// Storing execution times in a private field. Since background tasks are singleton objects this will keep its value
// while the application runs.
private int _count;

public DemoBackgroundTask(ILogger<DemoBackgroundTask> logger) => _logger = logger;

// Since background tasks are singletons we'll need this IServiceProvider instance to resolve every non-singleton
// service. When in doubt, just use this IServiceProvider instance to resolve everything instead of injecting a
// service via the constructor.
public async Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)
{
// This is where the task is implemented. Increment _count and print it to the error log with a message. Notice
// that there is a GetTaskName() extension method for IBackgroundTask which will return the technical name of
// the task. We use LogError() not because we're logging an error just so the message shows up in the log even
// with log levels ignoring e.g. info or debug entries. Use the logging methods appropriately otherwise!
_logger.LogError(
"Expected non-error - {Count}/{MaxCount}: Hello from {TaskName}!",
(++_count).ToTechnicalString(),
MaxCount,
this.GetTaskName());
// the task.

// Writing a message to the debug output, just so we can see this code running. This will be visible in output
// window of your IDE when running the app with the debugger attached.
Debug.WriteLine($"{(++_count).ToTechnicalString()}/{MaxCount}: Hello from {this.GetTaskName()}!");

if (_count == MaxCount)
{
Expand Down

0 comments on commit bdf7fc7

Please sign in to comment.