新建控制台程序Log4MongoDemo
通过NuGet安装Log4Net (v2.0.8)、log4mongo-net(v2.2.0)
项目根目录下添加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>
日志记录方法
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);
            }
        }
    }
记录日志
static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure(
               new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\log4net.config")
           );
            LogHelper.LogInfo(null);
            Console.ReadKey();
        }
查看结果

从github上下载【log4mongo-net】源码进行修改,日志中记录的字段定义在BackwardCompatibility.cs下BuildBsonDocument方法和BuildExceptionBsonDocument方法中,只需要修改这两个方法就可以按照根据自己的需求记录日志内容
将自定义的日志内容通过 log.Info(object) 传递
在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;
		}
	}
日志记录:LogHelper.LogInfo(object),object为自定义类型
因为MongoDb不需要预先定义集合结构,所以我们只需要根据自己的需求修改集合的生成规则就可以拆分日志到不同的集合中,这里实现将日志按天拆分。
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
Log4Net + Log4Mongo 将日志记录到MongoDb中
原文:https://www.cnblogs.com/zhaorong0912/p/13597936.html