Skip to content

Commit

Permalink
Writing debug messages to the Debug output and not the log files (it'…
Browse files Browse the repository at this point in the history
…s more appropriate and doesn't complicate UI testing)
  • Loading branch information
Piedone committed Jul 9, 2024
1 parent ad9e41c commit ac6668c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 23 deletions.
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 ac6668c

Please sign in to comment.