C
C#3w ago
velreine

ILogger<T> extension method "pass the args".

I am trying to create an extension method on ILogger<T> called LogPermissionDenied. I have a custom IPermissionDeniedErrorFragment which is an auto-generated interface from Strawberry shake based on a GraphQL fragment, that doesn't really matter that much, it is just to provide some context. The ILogger<T> has a method called LogError with an overload that accepts an string message and a params object?[] args I want to be able to call the LogPermissionDenied function and call it with a string that is contextual to the location it occurs in the code, the extension method should then append some more information regarding the permission that was denied. Here is the implementation of the extension method itself (I have attempted a few things but this is what it looks like so far.)
public static void LogPermissionDenied<T>(
this ILogger<T> logger,
[StructuredMessageTemplate] string message,
IPermissionFragment permission,
params object?[] args)
{
//object?[] newArgs = args.Append(new [])

var messageFormat = "Hello {name}";

var formattedMessage = string.Format(message, args);


logger.LogWarning("""
{errorMessage}
(Permission):
Id: {permissionId}
Name: {permissionName}
Description: {permissionDescription}
""", formattedMessage, permission.Id, permission.Name, permission.Description);
}
public static void LogPermissionDenied<T>(
this ILogger<T> logger,
[StructuredMessageTemplate] string message,
IPermissionFragment permission,
params object?[] args)
{
//object?[] newArgs = args.Append(new [])

var messageFormat = "Hello {name}";

var formattedMessage = string.Format(message, args);


logger.LogWarning("""
{errorMessage}
(Permission):
Id: {permissionId}
Name: {permissionName}
Description: {permissionDescription}
""", formattedMessage, permission.Id, permission.Name, permission.Description);
}
This is how i want to use that extension method:
this._logger.LogPermissionDenied("""
Doing business logic related thing for entity with id: {entityId} failed due to insufficient permissions.
""", permissionDeniedError.Permission!, entityId);
this._logger.LogPermissionDenied("""
Doing business logic related thing for entity with id: {entityId} failed due to insufficient permissions.
""", permissionDeniedError.Permission!, entityId);
Its important the params will appear in customDimensions in Application Insights, and that it is not possible to "screw up" the params (since they are positional). Any ideas?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server