80 lines
2.9 KiB
Java
80 lines
2.9 KiB
Java
package zw.qantra.tm.utils;
|
|
|
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
|
import com.fasterxml.jackson.databind.util.StdDateFormat;
|
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
|
import org.slf4j.Logger;
|
|
|
|
/**
|
|
* Utility class for pretty printing JSON in logs
|
|
*/
|
|
public class LogUtils {
|
|
|
|
private static final ObjectMapper prettyMapper = new ObjectMapper()
|
|
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
|
|
.setDateFormat(new StdDateFormat().withColonInTimeZone(true))
|
|
.registerModule(new JavaTimeModule())
|
|
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
|
|
.enable(SerializationFeature.INDENT_OUTPUT);
|
|
|
|
/**
|
|
* Log an object as pretty JSON
|
|
* @param logger The SLF4J logger instance
|
|
* @param level The log level (info, debug, etc.)
|
|
* @param message The log message
|
|
* @param object The object to pretty print
|
|
*/
|
|
public static void logPrettyJson(Logger logger, String level, String message, Object object) {
|
|
try {
|
|
String prettyJson = prettyMapper.writeValueAsString(object);
|
|
switch (level.toLowerCase()) {
|
|
case "debug":
|
|
logger.debug("{}:\n{}", message, prettyJson);
|
|
break;
|
|
case "info":
|
|
logger.info("{}:\n{}", message, prettyJson);
|
|
break;
|
|
case "warn":
|
|
logger.warn("{}:\n{}", message, prettyJson);
|
|
break;
|
|
case "error":
|
|
logger.error("{}:\n{}", message, prettyJson);
|
|
break;
|
|
case "trace":
|
|
logger.trace("{}:\n{}", message, prettyJson);
|
|
break;
|
|
default:
|
|
logger.info("{}:\n{}", message, prettyJson);
|
|
}
|
|
} catch (JsonProcessingException e) {
|
|
logger.error("Failed to pretty print JSON: {}", e.getMessage());
|
|
logger.info("{}: {}", message, object);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Log an object as pretty JSON at INFO level
|
|
* @param logger The SLF4J logger instance
|
|
* @param message The log message
|
|
* @param object The object to pretty print
|
|
*/
|
|
public static void logPrettyJson(Logger logger, String message, Object object) {
|
|
logPrettyJson(logger, "info", message, object);
|
|
}
|
|
|
|
/**
|
|
* Get pretty JSON string from object
|
|
* @param object The object to convert
|
|
* @return Pretty formatted JSON string
|
|
*/
|
|
public static String toPrettyJson(Object object) {
|
|
try {
|
|
return prettyMapper.writeValueAsString(object);
|
|
} catch (JsonProcessingException e) {
|
|
return object.toString();
|
|
}
|
|
}
|
|
} |