log4net unique request id in ASP.NET

log4net 1.2.11.0

I am trying to get anything that will allow me to log with a unique value for each ASP.NET request.

I tried %thread, but threads appear to be reused.

I’ve tried %aspnet-request and %aspnet-session which don’t have anything meaningful within them.

I looked at ThreadContext.Properties and LogicalThreadContext.Properties but they don’t have anything in them either.

Anyone have a trick to get this done? I need the ability to pick a particular request’s logs out of the log file.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

.asmx files will still call Application_BeginRequest event where you can store your unique GUID in HttpContext.Current.Items (using this collection avoid the odd problem when the request processing jumps threads). Only if you were using WCF (and also then it depends on configuration) this would not work.

If you would like not to touch the application itself, you can use HttpContext.Current.Timestamp that returns the time when the request processing started. Join that with your existing approach of getting the ID of the thread and you will get a unique value.

Method 2

HttpContext.Current.Items – is a good idea.

Try to add something like thit:

HttpContext.Current.Items.Add("RequestIdentity", Guid.NewGuid().ToString())

In .NET Core you can access it this way (from your controllers) HttpContext.Items and using HttpContextAccessor from anywhere else.

All the details here.

Method 3

clock tick + process ID + thread ID as stored when your request starts should be sufficient, I think (assuming each thread handles 1 request at a time).

Method 4

Here’s some extension methods that I created for this purpose:

public static Guid GetId(this HttpContext ctx) => new HttpContextWrapper(ctx).GetId();

public static Guid GetId(this HttpContextBase ctx)
{
    const string key = "tq8OuyxHpDgkRg54klfpqg== (Request Id Key)";

    if (ctx.Items.Contains(key))
        return (Guid) ctx.Items[key];

    var mutex = string.Intern($"{key}:{ctx.GetHashCode()}");
    lock (mutex)
    {
        if (!ctx.Items.Contains(key))
            ctx.Items[key] = Guid.NewGuid();

        return (Guid) ctx.Items[key];
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x