Best practices for using Markers in SLF4J/Logback

后端 未结 5 1034
花落未央
花落未央 2020-12-12 08:18

We are using SLF4J+Logback combination at our project for a while now and are quite happy with it, but our logging strategy is fairly simple, using straightforward class bas

5条回答
  •  温柔的废话
    2020-12-12 08:58

    First, MDC.

    MDC is really useful in an environment where you have one "entity" that is associated with some behaviour. A typical example: user interacting with a web application. So, let's say you have many users messing around with your web app. Using MDC, you can easily track them without too much hassle. Simplified example:

    ...[Sandy][abcd] clicked on "change profile"
    ...[Joe][1234] clicked on "weather reports"
    ...[Joe][1234] clicked on "Europe"
    ...[Sandy][abcd] clicked on "logout"
    ...[Joe][1234] clicked on "logout"
    ...[Sandy][efgh] logged in
    

    Here, you're using MDC in two places: for username and for session ID. This way, you can easily grep one user's session to see everything they've been doing.

    Second, markers.

    Markers are usually used for "special" circumstances, such as sending an email to an administrator for some seriously critical errors. Not all errors always fall in the same category; some have to be dealt in an appropriate way.

    Or, when a user quits from your service, it usually goes to an INFO log, but you can also use a marker for such instances, if you want events such as this one to go in a separate log file, so you can monitor it more easily for statistical gathering of users quitting.

    Rule of thumb:

    • MDC is used for associating multiple events with few "entities"
    • markers are used for "special" events that you want to have filtered from usual ones

提交回复
热议问题