Log4Net + Log4Mongo 将日志记录到MongoDb中

实现:

  1. 将日志保存在MongoDb中;
  2. 自定义日志字段;
  3. 日志按照日期拆分集合;

第一部分:将日志保存在MongoDb中

  1. 新建控制台程序Log4MongoDemo

  2. 通过NuGet安装Log4Net (v2.0.8)、log4mongo-net(v2.2.0)

  3. 项目根目录下添加log4net.config配置文件

    <?xml version="1.0"?>
    <configuration>
      <!--声明一个名为“log4net”的自定义配置节-->
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
      </configSections>
      <!--log4net配置信息-->
      <log4net>
        <logger name="MongoDBLogger">
          <level value="ALL"/>
          <appender-ref ref="MongoDBAppender" />
        </logger>
        <appender name="MongoDBAppender" type="Log4Mongo.MongoDBAppender, Log4Mongo">
          <connectionString value="mongodb://(登录名):(密码)@(服务器地址)/app" />
          <CollectionName value="logs"/>
        </appender>
      </log4net>
    </configuration>
    
  4. 日志记录方法

    public class LogHelper
        {
            private static readonly ILog log = LogManager.GetLogger("MongoDBLogger");
            /// <summary>
            /// 记录一般日志
            /// </summary>
            public static void LogInfo(AppOpLog opLog)
            {
                if (log.IsInfoEnabled)
                {
                    log.Info(opLog);
                }
            }
        }
    
  5. 记录日志

    static void Main(string[] args)
            {
                log4net.Config.XmlConfigurator.Configure(
                   new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\log4net.config")
               );
                LogHelper.LogInfo(null);
                Console.ReadKey();
            }
    
  6. 查看结果

第二部分:自定义日志字段

从github上下载【log4mongo-net】源码进行修改,日志中记录的字段定义在BackwardCompatibility.cs下BuildBsonDocument方法和BuildExceptionBsonDocument方法中,只需要修改这两个方法就可以按照根据自己的需求记录日志内容

  1. 将自定义的日志内容通过 log.Info(object) 传递

  2. 在BuildBsonDocument方法中通过LoggingEvent的MessageObject属性来获取自定义的日志内容

    public class BackwardCompatibility
    	{
    		public static BsonDocument BuildBsonDocument(LoggingEvent loggingEvent)
    		{
    			if(loggingEvent == null)
    			{
    				return null;
    			}
    
                BsonDocument bs = loggingEvent.MessageObject.ToBsonDocument();
                var toReturn = bs;
                toReturn.Add("TimeStamp", loggingEvent.TimeStamp);
                toReturn.Add("ThreadId", loggingEvent.ThreadName);
    
    			if(loggingEvent.ExceptionObject != null)
    			{
    				toReturn.Add("Exception", BuildExceptionBsonDocument(loggingEvent.ExceptionObject));
    			}
    
    			PropertiesDictionary compositeProperties = loggingEvent.GetProperties();
    			if(compositeProperties != null && compositeProperties.Count > 0)
    			{
    				var properties = new BsonDocument();
    				foreach(DictionaryEntry entry in compositeProperties)
    				{
    					properties.Add(entry.Key.ToString(), entry.Value.ToString());
    				}
    
    				toReturn.Add("Properties", properties);
    			}
    
    			return toReturn;
    		}
    
    		private static BsonDocument BuildExceptionBsonDocument(Exception ex)
    		{
    			var toReturn = new BsonDocument {
    				{"Message", ex.Message}, 
    				{"Source", ex.Source}, 
    				{"StackTrace", ex.StackTrace}
    			};
    
    			if(ex.InnerException != null)
    			{
    				toReturn.Add("InnerException", BuildExceptionBsonDocument(ex.InnerException));
    			}
    
    			return toReturn;
    		}
    	}
    
  3. 日志记录:LogHelper.LogInfo(object),object为自定义类型

第三部分:日志按照日期拆分集合

因为MongoDb不需要预先定义集合结构,所以我们只需要根据自己的需求修改集合的生成规则就可以拆分日志到不同的集合中,这里实现将日志按天拆分。

  1. 在log4net.config配置文件中将CollectionName的value修改为“yyyyMMdd”
  2. 修改MongoDBAppender.cs下的GetCollection()方法:
private IMongoCollection<BsonDocument> GetCollection()
		{
			var db = GetDatabase();
			var collectionName = CollectionName ?? "logs";

            if (collectionName == "yyyyMMdd")
            {
                collectionName = $"Log{DateTime.Now.ToString("yyyyMMdd")}" ;
            }

            EnsureCollectionExists(db, collectionName);

            var collection = db.GetCollection<BsonDocument>(collectionName);
			return collection;
		}

完整代码地址:https://github.com/zhrong92/Log4NetDemo

参考文章:https://www.cnblogs.com/zeallag/p/5205571.html

原文地址:https://www.cnblogs.com/zhaorong0912/p/13597936.html