views:

201

answers:

2

Please refer to: http://stackoverflow.com/questions/1340643/how-to-enable-ip-address-logging-with-log4net which explains how to log an IP using log4net.

My problem is that in certain cases extra threads are spawned that belong to a session. Now I need log4net to understand (or the thread) to be able to log with the correct IP.

Currently when an additional Thread is spawned the thread logs to the logfile as (null) instead of an IP.

How do I ensure that all threads related to a Session know the IP of the remote host?

+2  A: 
  1. Have the session know the IP address it is dealing with.
  2. When a new thread is created for that session, give it the IP address, either in the constructor or via a setter, before it is started.
  3. Have the thread put that information in ThreadContext.Properties when it starts running.

You may have to modify this slightly if you are using a thread pool, but the basic principle would be the same.

Vinay Sajip
+2  A: 

The solution was:

public static class MyLogManager
{
    public static ILog GetThreadAwareIPLogger(string loggerid)
    {
        if (log4net.ThreadContext.Properties["ip"] == null || !string.IsNullOrEmpty(log4net.ThreadContext.Properties["ip"].ToString()))
            log4net.ThreadContext.Properties["ip"] = HttpContext.Current.Request.UserHostAddress.PadLeft(15);

        return LogManager.GetLogger(loggerid);
    }
}

This is just a beginning of the solution. The point is to make a new Thread-Aware/Session-Aware Logger-factory, by using the (otherwise) sealed class inside your own public static class.

I get a log4net ILog instance that knows from which Session it was created/spawned and automatically sets the IP in the thread's ThreadContext when you request a new logger. Hope this helps someone else :-)

CodeMonkey