以编程方式配置 log4net,但额外的日志记录将转到控制台

Configuring log4net programmatically, but extra logging going to console

我已经从 Can you configure log4net in code instead of using a config file? 中获取代码并将其放入我的小 NET5 应用程序中。到目前为止,日志文件似乎没问题,但由于我没有配置任何进入控制台的附加程序,而只有一个滚动文件附加程序,所以我没想到任何东西都会进入控制台。然而,这正是正在发生的事情——我的消息将以不同的格式发送到控制台,它也没有使用我的模式布局。

这是我目前要设置的内容:

    private void SetupLog4Net()
    {
        var hierarchy = (Hierarchy)LogManager.GetRepository();
        hierarchy.Root.RemoveAllAppenders();
        hierarchy.Root.Level = Level.Debug;
        
        var patternLayout = new PatternLayout
        {
            ConversionPattern = "%date{yyyy-MM-dd HH:mm:ss.fff} [%logger] %message%newline%exception",
        };
        patternLayout.ActivateOptions();
        
        var rollingFileAppender = new RollingFileAppender
        {
            AppendToFile = true,
            File = @"Logs/uav.log",
            Layout = patternLayout,
            MaxSizeRollBackups = 5,
            MaxFileSize = 1_000_000,
            RollingStyle = RollingFileAppender.RollingMode.Size,
            StaticLogFileName = true,
            Encoding = System.Text.Encoding.UTF8,
        };
        rollingFileAppender.ActivateOptions();
        hierarchy.Root.AddAppender(rollingFileAppender);

        hierarchy.Root.Level = Level.Info;
        hierarchy.Configured = true;
        BasicConfigurator.Configure(hierarchy);
    }

这被称为 Main 所做的第一件事(构造应用程序对象,这是通过该构造函数调用的),然后我们才开始做任何其他事情。

然后,稍后,当我们调用记录内容时,例如,

       var logger = LogManager.GetLogger(this.GetType());
       logger.Info(message.Message, message.Exception);

我得到如下输出:

1780 [6] INFO MyClass.MainApp (null) - Ready

我什至无法理解其中的一半,但理解不是重点 - 清除此 appender 才是。对实际配置的评论作为评论很好,但主要问题是如何删除该控制台输出。

在 Linux

上使用 Log4NET 2.0.12 和 .NET 5.0.400

好的:所以您的 REAL 问题是“如何禁用 Log4Net 控制台日志记录?”

  1. 记住:在Java中,“log4j”是“记录器”。然而,在 .Net 中,Log4net 与 Microsoft.Extensions.Logging 共存。所以有“额外的东西”,这可能会产生“惊喜”。 .Net 本身(例如 Net 5,nee“.Net Core”)也可能产生“惊喜”。

  2. 具体来说,这里讨论了几种解决方案:

How do I disable log4net status messages to the console?

a. Change log4net.Config.BasicConfigurator.Configure(); to log4net.Config.XmlConfigurator.Configure();

b. set debug = false

c. Modify "log4net.Internal.Debug" in your app config file (e.g. "appsettings.json")

<appSettings>
   <add key="log4net.Internal.Debug" value="false"/>

另请参阅 Log4Net 常见问题解答:

http://logging.apache.org/log4net/release/faq.html

Internal debugging messages are written to the console and to the System.Diagnostics.Trace system. If the application does not have a console the messages logged there will be lost. Note that an application can redirect the console stream by setting the System.Console.Out.

As log4net internal debug messages are written to the System.Diagnostics.Trace system it is possible to redirect those messages to a local file.

根据 log4net 配置页面,调用 BasicConfigurator.Configure() 方法将“设置一个在控制台上登录的简单配置。”。 =12=]

鉴于您已经以编程方式将内容配置为写入文件,因此无需包含以下行:

BasicConfigurator.Configure();