Reputation:
Please refer to: 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?
Upvotes: 2
Views: 1846
Reputation:
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 :-)
Upvotes: 4
Reputation: 99365
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.
Upvotes: 1