Issue
I have a specific requirement needed in my project is to store logging data in my MongoDB database. There are lots of blogs for storing logs in a relational database but I can't find anything that works with MongoDB.
After hours of searching, I found this Wordpress article but after implementing it nothing happened. Blog: https://assylias.wordpress.com/2013/03/22/a-simple-logback-appender-for-mongodb/?unapproved=1424&moderation-hash=a5ff2a0d2832b77e2d7c0be3173ea667#comment-1424
But it's not working
Problem: I need to persist the log data to MongoDB.
Does anyone know how to append log data into MongoDB with Spring Boot?
Edit: I've figured a way around how to do it but it can be done with any type of database no matter MySQL or MongoDB. I'm providing the answer to how I did it but the question is still open. If anyone knows how to do it feel free to answer it and if it works I will accept the answer.
Solution
So the trick here is making a custom method that returns a string to the Logger class and saves the data to the database(any database relational or NoSQL doesn't matter). I will try to explain the whole scenario:
This is a document that will store the data to the MongoDB
@Document
public class Logs {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private Date date;
private String level;
private String message;
//getters and setters
}
If you are using MySQL you can use @Entity. Then create a MongoRepository of this class or CrudRepository if using JPA
public interface LogsRepository extends MongoRepository<Logs, String> {
}
Now you have to make a CustomLogger class which is used to insert data to the database
@Component
public class CustomLogger{
@Autowired
MongoTemplate mongoTemplate;
public String info(String message) {
Logs logs = new Logs();
logs.setLevel("INFO");
logs.setMessage(message);
logs.setDate(new Date());
mongoTemplate.insert(loggerDetail);
return message;
// same for other methods like debug(), error(), etc
}
Here I used MongoTemplate instead of LogsRepostiry to save data because Mongo allow to insert data if extends MongoRepository of every class
Now all you have to do is autowire this component to the class where you are using the logger. For my case it was a controller. When I'm hitting an API logs will show in console and also will save to the database
@RestController
public class LogsController {
@Autowired
CustomLogger customLogger;
Logger logger = LoggerFactory.getLogger(CustomLogger.class);
@GetMapping("/logger")
public String basicControllerToSaveData() {
logger.info(customLogger.info("Saving Logs to database"));
return "Success";
}
}
This will do the trick!
Answered By - Vince D