如何使用Log4Net登录每个线程的单独文件? [英] How to log into separate files per thread with Log4Net?

查看:165
本文介绍了如何使用Log4Net登录每个线程的单独文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用了多个具有明确定义的名称的线程(即不是具有匿名"线程的线程池).现在,所有这些线程都将它们的日志消息发送到一个文件-尽管线程ID是日志行的一部分,但这使分析应用程序行为变得非常困难.因此,我希望每个线程都可以登录到自己的日志文件中.

My application uses several threads with well-defined names (i.e. not a thread pool with 'anonymous' threads). Right now, all of these threads send their log messages to one file - and although the thread ID is part of the log line, this makes it very hard to analyse the application behaviour. Thus, I want each thread to log into its own log file.

似乎Log4Net没有提供内置选项来基于线程选择附加器.有人知道解决方案吗?请注意,我显然希望不切换到另一个日志记录库.

It seems that Log4Net offers no built-in option to choose an appender based on the thread. Does anyone know of a solution to this? Note that I obviously would prefer to not switch to another logging library.

推荐答案

选择"附加程序的log4net方法是通过过滤.在您的方案中,您需要一种方法来设置许多附加程序,每个附加程序代表一个定义良好的线程,并且在每个附加程序中都具有过滤器,仅通过来自各自线程的消息来传递消息.

The log4net way of "choosing" appenders is through filtering. In your scenario you would need a way of setting up a number of appenders, each representing a well-defined thread, and have filters in each appender passing through messages only from their respective thread.

由于线程ID不确定,因此您需要其他一些内容来进行过滤.我假设您自己控制这些线程的创建,并建议每个线程在 ThreadContext .接下来,您可以使用 PropertyFilter 来过滤消息根据标识符.

Since thread ID is not deterministic you will need something else to do your filtering on. I assume you are controlling the creation of these threads yourself and suggests that each thread registers an identifier in a property in the ThreadContext. Next you can then use the PropertyFilter to filter messages based on the identifiers.

这是一个示例配置设置,其中包含两个附加程序,每个附加程序都在消息中附加属性 threadId 的当前值与给定标识符匹配的消息.

Here's a sample config setup that have two appenders, each appending messages where the current value of property threadId matches a given identifier.

<appender name="x">
    <filter type="log4net.Filter.Property">
        <key value="threadId" />
        <stringToMatch value="threadX" />
    </filter>
    <filter type="log4net.Filter.DenyAllFilter" />
    ...
</appender>

<appender name="y">
    <filter type="log4net.Filter.Property">
        <key value="threadId" />
        <stringToMatch value="threadY" />
    </filter>
    <filter type="log4net.Filter.DenyAllFilter" />
    ...
</appender>

<root>
    <appender-ref name="x" />
    <appender-ref name="y" />
</root>

这篇关于如何使用Log4Net登录每个线程的单独文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆