读书人

利用log4mongo-java+mongodb复制集筹建

发布时间: 2012-10-23 12:12:21 作者: rapoo

利用log4mongo-java+mongodb复制集搭建java日志系统
可以将log4j的日志文件写入到mongodb中,原文方法如下

  1. Download and install MongoDB from http://www.mongodb.org/downloads
  2. Start mongod running on localhost on the default port
  3. Download the Mongo Java driver jarfile
  4. Download Log4J jarfile
  5. Download log4mongo-java jarfile
  6. Place these three jar files in your classpath
  7. Create a file called log4j.properties in your classpath
  8. Add the following lines to the log4j.properties file
    1. log4j.rootLogger=INFO, MongoDB
    2. log4j.appender.MongoDB=org.log4mongo.MongoDbAppender
    3. log4j.appender.MongoDB.databaseName=appname
    4. log4j.appender.MongoDB.collectionName=log
  9. Create a Java class like:
说明:1、下载mongodb,如果你已经安装过mongodb了,可以直接略过这一步,否则参考http://blog.csdn.net/jaysuper/article/details/8021806描述搭建2、启动mongod运行到本机和默认端口(localhost:27017),我们采取以前做过的案例Server201和Server202虚拟机进行测试。3、下载Mongo的java驱动文件,我们采用以前做过案例中使用的mongo-2.8.0.jar4、下载log4j文件,写过java的应该都有这个文件。5、下载log4mongo-java,我们下载的版本为log4mongo-java-0.7.0.jar6、将相关jar文件都加入到测试工程的classpath中7、在工程中创建一个log4j.properties文件,我们采取的配置如下
log4j.appender.MongoDB.hostname=mongo1.example.com mongo2.example.com

If MongoDB is listening on the same port on each host, you can specify just that port. If it's the default port of 27017, you can omit the property.

log4j.appender.MongoDB.port=27000

If the same port is not used by each host, then you must specify the port for all hosts. For example, if the hosts mongo1 and mongo2 are listening on 27000 and 28000, respectively:

log4j.appender.MongoDB.port=27000 28000

When a master becomes available, the next attempt to log will fail and the insert will be lost. The Mongo driver will then check for the new master and the next insert should go to the new master. Log inserts between the time of the original master's failure and the election of the new master will be lost.


所以我们的配置改为如下
log4j.appender.MongoDB.hostname=Server202 Server201log4j.appender.MongoDB.port=10001 10002

总结:1、可以将日志放置在mongdb放置到2台服务器上,便于日志分析和备份。2、每个程序可以使用一个db,也可以每个程序使用一个collection。3、无需更改现有程序的代码,增加简单配置即可实现。4、mongodb下的db目录所属磁盘满了之后,不影响程序的正常运行,程序也不会报错,只不过不会再写入日志。







读书人网 >其他数据库

热点推荐