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 Sessi开发者_如何学编程on know the IP of the remote host?
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 :-)
- Have the session know the IP address it is dealing with.
- 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.
- 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.
精彩评论