log4net 日志写入MongoDB 实现分布式日志

本人在.net framework 4.0下测试成功,首先需要安装log4mongo-net组件,见https://www.nuget.org/packages/log4mongo-net/

vs2012以上直接使用PM命令 Install-Package log4mongo-net 下载安装

log4net 配置文件修改如下:

<?xml version="1.0" encoding="utf-8"?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="log/"/>
    <param name="AppendToFile" value="true"/>
    <param name="MaxSizeRollBackups" value="10"/>
    <param name="StaticLogFileName" value="false"/>
    <param name="DatePattern" value="yyyy-MM-dd&quot;.log&quot;"/>
    <param name="RollingStyle" value="Date"/>
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n%n"/>
    </layout>
  </appender>
  <appender name="DUMLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="Dumlog/"/>
    <param name="AppendToFile" value="true"/>
    <param name="MaxSizeRollBackups" value="10"/>
    <param name="StaticLogFileName" value="false"/>
    <param name="DatePattern" value="yyyy-MM-dd&quot;.log&quot;"/>
    <param name="RollingStyle" value="Composite"/>
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n%n"/>
    </layout>
  </appender>
  <appender name="MongoDBAppender" type="Log4Mongo.MongoDBAppender, Log4Mongo">
    <connectionString value="mongodb://192.168.0.226:6111/?socketTimeout=1s" />
    <CollectionName value="Wilson.Log4Net"/>
  </appender>

  <root>
    <level value="ALL" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>  
  <logger name="TopeveryByDUM">
    <level value="ALL"/>
    <appender-ref ref="MongoDBAppender" />
  </logger>
</log4net>

C#源代码:

class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            log4net.ILog Log = log4net.LogManager.GetLogger("TopeveryByDUM");
            for (int i = 0; i < 10000; i++)
            {
                Console.WriteLine(i);
                Log.DebugFormat("Wilson_测试日志内容__{0}", i);
            }
        }
    }

运行结果如下,写入1W条日志耗时2秒左右。

log4net 日志写入MongoDB 实现分布式日志_第1张图片

 

log4net 日志写入MongoDB 实现分布式日志_第2张图片

 

你可能感兴趣的:(log4net 日志写入MongoDB 实现分布式日志)