Home > front end >  Capture and change all logging message
Capture and change all logging message

Time:12-01

I have an ASP.NET Core 5 application. There are some log providers that I have as from box. Other words I cannot configure theese providers. But I need to add additional info to every logging message.

For example, code invoke:

logger.LogInfo("Hello World");

But logging provider must get, for example "UserId: 123; Hello World"

How can I reach this goal?

CodePudding user response:

you can create an extension method for this like this,

public static class LogExtensions
{
    public static void CustomLogInformation(this ILogger log, string message)
    {
        log.LogInformation($"prefix{message}");
    }
}

you could also pass Exception exception as a parameter if you require it.

In this example, prefix is added, but you can change the value as per your requirements.

If the prefix values changes then you can pass that as well by adding one more parameter to this method. If it's the same for all scenarios then you can define it in some config file.

and if you look at the source code, LogInformation itself is an extension method.

namespace Microsoft.Extensions.Logging
{
    public static class LoggerExtensions
    {

        public static void LogInformation(this ILogger logger, string message, params object[] args)
        {
            logger.Log(LogLevel.Information, message, args);
        }
    }
}

CodePudding user response:

NLog Layout enables you to capture additional NLog Context besides what is provided with the actual logevent.

You could update your NLog Target Layout to include ${aspnet-user-identity} in the output:

<target xsi:type="console"
        name="console"
        layout="${aspnet-user-identity} ${level} ${message}" />

Another alternative could be ${aspnet-user-claim:ClaimTypes.Name}. If your user-information comes from custom location, then you can also implement a custom layout-renderer.

  • Related