Apache Log4net C# Console Demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Empty_Android/article/details/83653331

官网上的实例代码,自己修改后实现的demo.

1. 添加引用

解决方案视图,右键引用,搜索并安装

2. 项目树

3. 代码

这里用的读取xml方式初始化配置log4net.

Log4NetConfig.xml

此文件放在代码同级目录,并拷贝到debug和release中

这里配置输出错误日志到根目录log.txt

<log4net>
  <appender name="Console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <!-- Pattern to output the caller's file name and line number -->
      <conversionPattern value="%date %5level [%thread] (%file:%line) - %message%newline" />
    </layout>
  </appender>

  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="log" />
    <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level [%thread] (%file:%line) - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="Console" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

Program.cs

using Com.foo;

// Import log4net classes.
using log4net;
using log4net.Config;
using System.IO;

namespace ConsoleApp_ApacheLog4net
{
    class MyApp
    {
        // Define a static logger variable so that it references the
        // Logger instance named "MyApp".
        private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));

        static void Main(string[] args)
        {
            // Set up a simple configuration that logs on the console.
            // BasicConfigurator.Configure();

            string log4netConfigPath = "Log4NetConfig.xml";

            if (File.Exists(log4netConfigPath))
            {
                // Load config file
                XmlConfigurator.Configure(new System.IO.FileInfo(log4netConfigPath));

                // Reload the config each time the file is modified
                XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo((log4netConfigPath)));
            }

            log.Info("Entering application.");
            Bar bar = new Bar();
            bar.DoIt();
            log.Info("Exiting application.");

            try
            {
                int test = 0;
                int result = 100 / test;
            }
            catch (System.Exception ex)
            {
                log.Error(ex.Message);
            }
        }
    }
}

Bar.cs

// Import log4net classes.
using log4net;

namespace Com.foo
{
    public class Bar
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Bar));

        public void DoIt()
        {
            log.Warn("Did it again!");
        }
    }
}

4. 运行

断点调试

Txt

猜你喜欢

转载自blog.csdn.net/Empty_Android/article/details/83653331