logback日志存入mongodb

首先继承 logback 中的 ch.qos.logback.core.UnsynchronizedAppenderBase

public class MongoDBAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
@Override
protected void append(ILoggingEvent eventObject) {
MongoTemplate mongoTemplate = ApplicationContextProvider.getBean(MongoTemplate.class);
if (mongoTemplate != null) {
final BasicDBObject doc = new BasicDBObject();
doc.append("level", eventObject.getLevel().toString());
doc.append("logger", eventObject.getLoggerName());
doc.append("thread", eventObject.getThreadName());
doc.append("message", eventObject.getFormattedMessage());
mongoTemplate.insert(doc, "log");
}
}

}

这里呢我使用了spring-data-mongodb 不喜欢的朋友可以自己使用 mongo-java-driver 这里的 ApplicationContextProvider 代码如下

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;

public static ApplicationContext getApplicationContext() {
return context;
}

@Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}

public static <T> T getBean(Class<T> tClass) {
return context.getBean(tClass);
}

public static <T> T getBean(String name, Class<T> tClass) {
return context.getBean(name, tClass);
}
}

logback-spring.xml 中加入如下配置

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 文件输出格式 -->
<property name="PATTERN" value="%-1(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n"/>

<appender name="MONGO" class="com.fulinlin.log.MongoDBAppender"/>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${PATTERN}</pattern>
</encoder>
</appender>

<!-- 开发环境 -->
<springProfile name="dev">
<logger name="com.fulinlin" level="debug">
<appender-ref ref="MONGO"/>
</logger>
<root level="info">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>

</configuration>

然后就可以了 就是这么简单