1、继承UnsynchronizedAppenderBase
package com.xf.config; import java.util.Map; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.util.StringUtils; import com.alibaba.fastjson.JSONObject; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.UnsynchronizedAppenderBase; import cn.hutool.extra.spring.SpringUtil; import lombok.Data; @Data public class MongoDBAppender extends UnsynchronizedAppenderBase<LoggingEvent> { private MongoTemplate mongoTemplate; String appName; String collectionName; @Override protected void append(LoggingEvent e) { if (mongoTemplate == null) mongoTemplate = SpringUtil.getBean(MongoTemplate.class); JSONObject obj = new JSONObject(); obj.put("appName", appName); obj.put("Level", e.getLevel().toString()); obj.put("Message", e.getFormattedMessage()); obj.put("TimeStamp", e.getTimeStamp()); obj.put("Class", e.getCallerData()[0].toString()); Map<String, String> map = e.getMDCPropertyMap(); map.forEach((k, v) -> { obj.put(k, v); }); if (StringUtils.isEmpty(collectionName)) mongoTemplate.save(obj, "wjflog"); else mongoTemplate.save(obj, collectionName); } }
2、xml配置
<appender name="MONGODB" class="com.xf.config.MongoDBAppender"> <appName>odvapi</appName> <collectionName>mylog</collectionName> </appender>
3、mongdb配置
spring: data: mongodb: database: test port: 27017 host: 127.0.0.1