Log4Net 跨多个线程记录单个会话的 IP 地址

发布于 2024-08-12 01:39:50 字数 316 浏览 5 评论 0原文

请参考:如何使用Log4Net启用IP地址日志记录其中解释了如何使用 log4net 记录 IP。

我的问题是,在某些情况下,会产生属于会话的额外线程。现在我需要 log4net 来理解(或线程)才能使用正确的 IP 进行日志记录。

目前,当生成额外的线程时,线程会将日志记录为 (null) 而不是 IP。

如何确保与会话相关的所有线程都知道远程主机的 IP?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野心澎湃 2024-08-19 01:39:50

解决方案是:

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);
    }
}

这只是解决方案的开始。重点是通过在您自己的公共静态类中使用(否则)密封类来创建一个新的线程感知/会话感知记录器工厂。

我得到一个 log4net ILog 实例,它知道它是从哪个会话创建/生成的,并在您请求新记录器时自动在线程的 ThreadContext 中设置 IP。希望这对其他人有帮助:-)

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 :-)

固执像三岁 2024-08-19 01:39:50
  1. 让会话知道它正在处理的 IP 地址。
  2. 当为该会话创建新线程时,请在启动之前在构造函数中或通过 setter 为其提供 IP 地址。
  3. 让线程在开始运行时将该信息放入 ThreadContext.Properties 中。

如果您使用线程池,您可能需要稍微修改一下,但基本原理是相同的。

  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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文