项目里面需要记录大量的日志,为了方便分析,也是为了方便开发人员远程查询日志,可以把日志写入MongoDB.
1.先上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".log""/> <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="MongoDBAppender" type="Log4Mongo.MongoDBAppender, Log4Mongo"> <connectionString value="mongodb://127.0.0.1:2771/?socketTimeout=1s" /> <CollectionName value="API"/> </appender> <root> <level value="ALL" /> <appender-ref ref="RollingLogFileAppender" /> </root> <logger name="TopeveryByDUM"> <level value="ALL"/> <appender-ref ref="MongoDBAppender" /> </logger> </log4net>
2.使用 Nuget 获取 log4mongo-net 包
3.测试
log4net.Config.XmlConfigurator.Configure(); log4net.ILog Log = log4net.LogManager.GetLogger("API_TEST"); for (int i = 0; i < 10000; i++) { Log.DebugFormat("测试把日志写到 MongoDB", i); Console.WriteLine(i); }
4.其它: