When use spring boot, from time to time I need to log my objects like UserInfo, Person and another to log in json format
If I log just to put my object, logs looks like User@3242 (with hash code)
So I tried any ways to solve this issue, but every of this have many disadvantages
1)
log.info("hello {}", objectMapper.writeValueAsString(user))
but this way is not handy because I need try catch, user may cause npe, and I can forget to user objectMapper
crete console appender for json logs
true yyyy-MM-dd' 'HH:mm:ss.SSS true %d{yyyy-MM-dd HH:mm:ss} %-5p %m%n<root name="standard" level="info"> <appender-ref ref="stdout"/> </root> <logger name="jsonLogger" level="info"> <appender-ref ref="json"/> </logger>
but this way just transforms my logs in json but user put in message filed and write like simple toString()
- Override toString() on every object using ObjectMapper but this way is increas overhead of write new code
Do you know another handy way to log in json just my custom objects?
You can of course override the User class
toString()method and return the instance of of the current user object as string in the format you want, for example:Simple example of a User class:
How you might use:
The custom
toString()method within the User class should return something like:Change the
toString()method code to return whatever format you want.If however, you actually want to add a JSON or XML Compact-Print or Pretty-Print string to the log and you don't mind adding some Jackson API's to your project and add the following methods to your User class (be sure to read the JavaDoc for each method):
To produce a JSON String:
then try something like this:
For Pretty-Print:
For Compact-Print:
To produce a XML String:
then try something like this:
For Pretty-Print:
For Compact-Print: