首先存入和管理日志有elk,但是项目管理系统作为不是很大型的项目,就不想引入太多的组件
这样管理起来也很麻烦,于是就想着在已引入的mongodb上存储
1.自定义一个appender
public class LogbackToMongoAppender extends AppenderBase<LoggingEvent>{
// @Autowired
// private MongoTemplate mongoTemplate;
@Override
protected void append(LoggingEvent eventObject) {
MongoTemplate mongoTemplate = BeanHelper.getBean(MongoTemplate.class);
Logback logback=new Logback();
logback.setTimeStamp(eventObject.getTimeStamp());
logback.setCreateTime(DateHelper.DateToString(new Date(eventObject.getTimeStamp()), DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
logback.setContent(eventObject.toString());
logback.setLevel(eventObject.getLevel().levelStr);
logback.setLoggerName(eventObject.getLoggerName());
logback.setThreadName(eventObject.getThreadName());
mongoTemplate.save(logback);
}
}
2.所使用的实体类
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "logback")
public class Logback {
private String createTime;
private String content;
private String level;
private long timeStamp;
private String loggerName;
private String threadName;
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public String getLoggerName() {
return loggerName;
}
public void setLoggerName(String loggerName) {
this.loggerName = loggerName;
}
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
}
3.在logback xml文件中配置 新加一个appender标签(xx部分填定自已的包名)
<appender name="MyAppender" class="com.xx.log.LogbackToMongoAppender" />
在root里面加入定义的appender
<root level="debug">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="MyAppender" /> <!--这里是上面定义的appender-->
</root>