使用 Spring Boot 时,有时我需要记录 UserInfo、Person 等对象以 json 格式登录
如果我只是为了放置我的对象而登录,日志看起来像 User@3242 (带有哈希代码)
所以我尝试了各种方法来解决这个问题,但是每种方法都有很多缺点
1)
log.info("hello {}", objectMapper.writeValueAsString(user))
但是这种方式不太方便,因为我需要try catch,用户可能会导致npe,而且我可能会忘记使用objectMapper
用于 json 日志的 crete 控制台附加程序
真的 yyyy-MM-dd' 'HH:mm:ss.SSS 真的 %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>
但这种方式只是将我的日志转换为 json 但用户放入消息字段并像简单的 toString() 一样写入
您知道另一种方便的方法来登录 json 只是我的自定义对象吗?
您当然可以重写 User 类
toString()
方法并以您想要的格式将当前用户对象的实例作为字符串返回,例如:
User 类的简单示例:
public class User {
private String name;
private String password;
public User() {}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
// Custom toString() method:
@override
public String toString() {
StringBuilder sb = new StringBuilder("");
sb.append("User Object Instance: -> User Name: ");
sb.append(this.name).append(" - User Password: ");
sb.append(this.password);
return sb.toString();
}
}
如何使用:
log.info("hello {}", user.toString());
User
类中的自定义
toString()
方法应返回类似以下内容:
"User Object Instance: -> User Name: Fred Flintstone - User Password: MyPassword"
更改 toString()
方法代码以返回您想要的任何格式。但是,如果您确实想向日志添加 JSON 或 XML Compact-Print 或 Pretty-Print 字符串,并且您不介意向您的项目添加一些 Jackson API,并将以下方法添加到您的
User 类中(请务必阅读每个方法的 JavaDoc): 生成 JSON 字符串:
/**
* This method utilizes the following Jackson API jar files:
* Tested with:<pre>
* jackson-dataformat-xml-2.16.1.jar
* jackson-core-2.16.1.jar
* jackson-databind-2.16.1.jar
* jackson-annotations-2.16.1.jar
* stax2-api-4.2.1.jar
* woodstox-core-6.5.1.jar
* </pre>
*
* Converts this instance of User to a JSON string in either Compact-Print
* or in default Pretty-Print.<br>
*
* @param asCompactPrint (boolean - varArg - Optional) By default Compact-
* Print is false which tells the method to create the JSON string in a
* Pretty-Print format. If boolean <b>true</b> is supplied then a Compact-
* Print format JSON string is returned.
*
* @return (String) The current Object instance converted to a JSON String.
*/
public String toJSON (boolean... asCompactPrint) {
boolean compact = false;
if (asCompactPrint.length > 0) {
compact = asCompactPrint[0];
}
String resultString = "";
try {
com.fasterxml.jackson.databind.ObjectMapper mapper
= new com.fasterxml.jackson.databind.ObjectMapper();
if (compact) {
// Java object to Compact-Print JSON string:
resultString = mapper.writeValueAsString(this);
}
else {
// Java object to Pretty-Print JSON string:
resultString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
}
}
catch (com.fasterxml.jackson.core.JsonProcessingException ex) {
System.err.println(ex);
}
return resultString;
}
对于漂亮的印刷:
log.info("hello {}", user.toJSON());
对于紧凑打印:
log.info("hello {}", user.toJSON(true));
/**
* This method utilizes the following Jackson API jar files:
* Tested with:<pre>
* jackson-dataformat-xml-2.16.1.jar
* jackson-core-2.16.1.jar
* jackson-databind-2.16.1.jar
* jackson-annotations-2.16.1.jar
* stax2-api-4.2.1.jar
* woodstox-core-6.5.1.jar
* </pre>
*
* Converts this instance of User to a XML string in either Compact-Print
* or in default Pretty-Print.<br>
*
* @param asCompactPrint (boolean - varArg - Optional) By default Compact-
* Print is false which tells the method to create the XML string in a
* Pretty-Print format. If boolean <b>true</b> is supplied then a Compact-
* Print format XML string is returned.
*
* @return (String) The current Object instance converted to a XML String.
*/
public String toXML(boolean... asCompactPrint) {
boolean compactPrint = false;
if (asCompactPrint.length > 0) {
compactPrint = asCompactPrint[0];
}
String resultString = "";
try {
com.fasterxml.jackson.dataformat.xml.XmlMapper xmlMap =
new com.fasterxml.jackson.dataformat.xml.XmlMapper();
if (!compactPrint) {
resultString = xmlMap.writerWithDefaultPrettyPrinter().writeValueAsString(this);
}
else {
resultString = xmlMap.writeValueAsString(this);
}
}
catch (JsonProcessingException ex) {
System.err.println(ex);
}
return resultString;
}
对于漂亮的印刷:
log.info("hello {}", user.toXML());
对于紧凑打印:
log.info("hello {}", user.toXML(true));