I was trying to wrap a Logback logger in order to provide some handy methods and already defined default keys of the logged json output and I came up with something like this.
Do you spot any problem with it, or do you have any suggestion?
public class Log {
private Logger logger = LoggerFactory.getLogger("jsonLogger");
private String msg;
private long start;
private Map<String, Object> kvs;
private Log(String msg) {
this.msg = msg;
this.start = System.currentTimeMillis();
this.kvs = new HashMap<>();
}
public static Log msg(String msg) {
return new Log(msg);
}
public Log kv(String key, Object value) {
kvs.put(key, value);
return this;
}
public void log() {
kvs.put("elapsed", System.currentTimeMillis() - start);
List<StructuredArgument> args = new ArrayList<>();
for (String k : kvs.keySet()) {
args.add(StructuredArguments.kv(k, kvs.get(k)));
}
logger.info(msg, args.toArray());
}
}
In this way you can log just a message, custom key-values and have a way to keep track of the execution between a function:
// just a message
Log.msg("my message").log();
// message with custom kv or complex objects
Log.msg("my message").kv("foo", "bar").kv("arr", new String[]{"a", "b", "c"}).log();
// elapsed time
Log logger = Log.msg("my message").kv("foo", "bar");
Thread.sleep(1240);
logger.log();