Log4net简单使用

Log4net简单使用


1. Add log4net Package

Starting with log4net is as easy as installing a Nuget package. You can use the Visual Studio UI to search for it and install it, or just run this quick command from the Package Manager Console.

PM> Install-Package log4net

2. Add log4net.config file

Add a new file to your project in Visual Studio called log4net.config and be sure to set a property for the file. Set “Copy to Output Directory” to “Copy Always”. This is important because we need the log4net.config file to be copied to the bin folder when you build and run your app.
这里写图片描述

To get you started quickly, copy this log4net config and put it in your new log4net.config file. This will log messages to the console and a log file both. We will discuss more about logging appenders further down.

<log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="file" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="file" type="log4net.Appender.RollingFileAppender">
      <file value="myapp.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
  </log4net>

3. Tell log4net to Load Your Config

The next thing we need to do is tell log4net where to load it’s configuratin from so that it actually works. I suggest putting this in your AssemblyInfo.cs file. You can find it under the Properties section in your project.
这里写图片描述
Add this to the bottom of your AssemblyInfo file.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

这里可以自己定义文件路径,比如:

[assembly: log4net.Config.XmlConfigurator(ConfigFile =  @"APPData/LogData/log4net.config")]

4. Log Something!

Now you can modify your app to log something and try it out!

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

        static void Main(string[] args)
        {
            log.Info("Hello logging world!");
            Console.WriteLine("Hit enter");
            Console.ReadLine();
        }
    }

5. 更多

查看更多的功能:
log4net更多功能

猜你喜欢

转载自blog.csdn.net/m0_37591671/article/details/80197458
今日推荐