Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS logs not showing 'cs-username' field for .NET Core application

Tags:

.net

logging

iis

I have two existing applications running in IIS 8.5, one is ASP.NET and the other is .NET Core. The ASP.NET application is correctly writing the cs-username field in the IIS logs, but the .NET Core application only shows a hyphen.

I have found an article and a forum post which suggest adding some xml to the applicationhost.config file, but I don't have the <advancedlogging> branch it is referring to.

If the solution is to simply follow the article, then can someone explain why my config file isn't formatted like theirs and where I should put the suggested xml? Otherwise, are there any only solutions that anyone is aware of?

like image 961
Murphybro2 Avatar asked Oct 29 '25 04:10

Murphybro2


1 Answers

I have two workarounds for logging the username in asp.net core apps and IIS.

  1. In the core app add the user to the server variables and then in IIS log the custom field. This only works when using the In Process hosting model.

In your app add:

app.UseAuthentication();
app.Use(async (context, next) =>
{
    if (context.User.Identity.IsAuthenticated && context.Features.Get<IServerVariablesFeature>() is IServerVariablesFeature serverVariables)
    {
        serverVariables["AUTH_USER"] = context.User.Identity.Name ?? "?";
        serverVariables["AUTH_TYPE"] = context.User.Identity.AuthenticationType ?? "?";
    }
    await next.Invoke();
});

In your IIS site go to Logging > Select Fields > Add Field. Set Field Name: auth-user, Source Type: Server Variable, Source: AUTH_USER. Accept and apply all changes.

Using custom fields does cause IIS to use a different log file name. You might need to update your monitoring apps or scripts to see these files.

(Name can be null when an authentication service accepts the request but doesn't have enough information for all details. E.g. a SAML request that doesn't have the soap name attribute. I use the ? to distinguish it from the anonymous - in the logs.)

  1. Use the W3C Logger middleware. This does not log to the IIS log files but does log cs-username in its own log file. You will need to allow the app pool to have write permissions to the folder you choose to log to. It also means you may be logging the same information twice.
like image 158
Nicholas Avatar answered Oct 31 '25 22:10

Nicholas