Deal with it or don't

Get User Identity in your log4net

You want your website’s log4net logs to have the authenticated user’s name. Here’s all you do.

(credit to Gian Marco Gherardi)

Add this in your code (right after you call XmlConfigurator.Configure(…) would be fine.)

	GlobalContext.Properties["user"] = new HttpContextUserNameProvider();


	public class HttpContextUserNameProvider
		public override string ToString()
			HttpContext context = HttpContext.Current;
			if (context != null && context.User != null && context.User.Identity.IsAuthenticated)
				return context.User.Identity.Name;
			return "";

The, in your log4net config, you can use it with “%property{user}”
like so…

<conversionPattern value="%date %-5level %property{Category} [%property{user}] - %message%newline" />

Like a charm.

3 responses to “Get User Identity in your log4net

  1. rd1089 July 17, 2013 at 7:23 am

    Neat and simple. Thank you.

  2. rd1089 July 19, 2013 at 3:45 pm

    Reblogged this on rd1089 and commented:
    Since I had my log4net.Config.XmlConfigurator in AssemblyInfo.cs, I included the custom param (user) variable in Application_Start in Global.asax.cs. Kept everything else the same. Worked like a charm.

  3. Anon November 19, 2013 at 11:13 am

    …or just use [%identity] in log4net config.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: