简体   繁体   中英

How can I do structured logging?

Are there any logging libraries that allow for structured logging of objects, by which I mean, the output is in a structured form, such as JSON or XML?

At the application level, I want to use a terse syntax (logging tends to hide application code), such as

  1. logger.info("Deleting user", user)
  2. logger.info(part("Deleting user", user), part("Account", account), part("Something else", someValue));

At the log file level, I get well structured JSON (etc), with meta-data (thread, MDC, time, level, etc) as an envelope, with my own message as a structured JSON object within it, eg

"log" : {
  "time": <timestamp>,
  "level": "INFO",
  "thread": <thread-name>,
  "MDC": [MDC info added by application code],
  etc...
  "message": {
    "Message": "Deleting User",
    "User": <JSON object of the user serialised>
  }
}

Of course, it would not need to be pretty-printed in the log file.

It would be cool if the domain objects (eg User) could implement a Loggable interface that has methods to serialise state for different log-levels, eg

  1. INFO level gives a summary
  2. DEBUG level gives more, deeper data, recursively

*Some log aggregator could then make sense of the logs at a semantic level. Logs are consistently formatted allowing searching, etc.*

I have, in the past, implemented a couple of functions that get me part of the way, to ensure key/values pairs are formatted but that doesn't give me everything I want. This works, normalising key/values, formatting values, highlighting nulls, etc but it doesn't emit JSON and cannot delegate object formatting: -

logger.info(logString(part("Deleting user", user), part("Account", account), part("Something else", someValue)));

Any ideas?

您可以使用JSONObject.toString()方法在logcat上打印JSON。

Log.d("tag", jsonObject.toString(4));

This is the problem space addressed by message templates . The serilogj implementation in Java looks like:

Log.information("Deleting {@user}", user);

where @ indicates that the user property should be serialized into the event as structured data.

Even without serialization, message templates produce logs with first-class semantic properties. For example the event:

Log.information("Dividing {a} by {b}", 1, 0);

will produce an event with message Dividing 1 by 0 and properties a = 1 and b = 0 .

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