Using multiple log4net file loggers

守給你的承諾、 提交于 2020-01-04 02:54:12

问题


I have file appenders FileA, FileB, and FileC. FileA I add to the root element as I want it to be a catch all, (more on this below). FileB and FileC I use for specific messages and create named loggers for each of those appenders. In code, I load the log I'm using for most messages like so:

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

The other loggers, I load like this

private static readonly log4net.ILog commandLog = log4net.LogManager.GetLogger("LoggerFileB");

What's happening is I'm getting what I expect in LoggerFileB, ie, ONLY the special messages. The problem is these messages also showing up in LoggerFileA, my catch-all I added to root. I could create a specific named instance for the catch-all, instead of adding it to the root element, but I want the calling type as the logger name in the output. Creating a named logger means that %logger outputs the name of the log instead of the type. Is there a way to get precisely what I want (the catchall to show the logger name as the type, but not show messages logged to other named loggers)? Hopefully I'm missing something and there is a simple solution.

Here's an example of what my log.config looks like for this situation.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <log4net>
        <appender name="FileA" type="log4net.Appender.RollingFileAppender">
            <file value="FileA.txt" />
            ...snip...
        </appender>
        <appender name="FileB" type="log4net.Appender.RollingFileAppender">
            <file value="FileB.txt" />
            ...snip...
        </appender>
        <appender name="FileC" type="log4net.Appender.RollingFileAppender">
            <file value="FileC.txt" />
            ...snip...
        </appender>
        <root>
            <level value="ALL" />
            <appender-ref ref="LoggerFileA" />
        </root>
        <logger name="LoggerFileB">
            <level value="ALL" />
            <appender-ref ref="FileB" />
        </logger>
        <logger name="LoggerFileC">
            <level value="ALL" />
            <appender-ref ref="FileC" />
        </logger>
    </log4net>
</configuration>

回答1:


You can use set the additivity to false:

<logger name="LoggerFileB" additivity="false">


来源:https://stackoverflow.com/questions/4038237/using-multiple-log4net-file-loggers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!