简体   繁体   中英

Why do loggers in Java rarely have the .toString() that System.out.println does?

I'm frequently annoyed by having

System.out.println(someObject);

and, when changing it to using whatever logger is required

LOG.info(someObject);

and having to add the .toString() to make it compile

LOG.info(someObject.toString());

I cannot recall having used a logger that does not simply take in an Object and tries do to .toString() on it, making me wonder if there is a specific reason for this. Surely I cannot be the only one annoyed by having to add .toString() to everything?

The key point is to understand the purpose of logging. Loggers are there to print human readable english messages regarding any event that occurs within an application. And the logging API's are built following this basic principle

LOG.info(someObject.toString());

The problem with the above line is that the basic concept of logging is somewhat different from what you are trying to achieve. You want to log an object which is already not a human readable entity and then to make it work by casting it either to a string or you could implement the toString() method or lastly you can take a look at one of the overloaded function

public void info(String format, Object... arguments)

Logging an object directly is mostly done by developers when they want to debug to lets say the contents of the object or something like that, so the best way to achieve that would be to correctly implement the toString() method.

I would also advise to take a look into the Project Lombok , it provides ready to use implementations of common hashCode() and toString() functions of your beans so you don't have to go through your code and implement the method one by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM