Fluent interface for Logger












0














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();









share|improve this question
















bumped to the homepage by Community yesterday


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.




















    0














    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();









    share|improve this question
















    bumped to the homepage by Community yesterday


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.


















      0












      0








      0


      1





      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();









      share|improve this question















      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();






      java logging fluent-interface logback






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 4 '18 at 10:00









      t3chb0t

      34.1k746115




      34.1k746115










      asked Nov 3 '18 at 9:56









      EnrichmanEnrichman

      1213




      1213





      bumped to the homepage by Community yesterday


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community yesterday


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          1 Answer
          1






          active

          oldest

          votes


















          -1














          i do not think this is really a good idea (sorry to say that)...



          why is is not a good idea? it's breaking the concept of segregaton of concerns:




          1. a Logger is responsible for logging

          2. a Profiler is responsible for measuring execution time

          3. a Logger is NOT responsible for keeping track of items (who is responsible for cleaning these entries?)


          another issue i see is that you create a new logger whenever you want to write something into you log, i don't see any reason for that...



          what would i suggest?



          create a timesheet



          public class Timesheet{

          private final Map<TimeStamp, KeyValue kv> entries;
          private final Logger logger;

          public Timesheet(Logger logger){
          this.logger = logger
          entries= ...
          }

          public Timesheet kv(Object key, Object value) {
          TimeStamp timestamp = new TimeStamp();
          entries.put(timestamp , new KeyValue(key, value));
          log.debug("adding key/value {}/{} at {}", key, value, timestamp );
          return this;
          }

          public Timesheet msg(Object msg) {
          logger.debug(msg);
          return this;
          }

          public Timesheet elapsed() {
          logger.debug("time elapsed {}", calculateTimeElapsed());
          return this;
          }

          }


          not all is implemented here, it should just girve you an idea of how you could do it...



          Timesheet timesheet = new Timesheet(LoggerFactory.getLogger("jsonLogger")); //now availible for all classes
          timesheet.msg("hello");
          timesheet.kv("foo", "bar");
          Thread.sleep(1234);
          timesheet.elapsed();


          some final words...



          i think it is not a good idea of using KeyValue pairs - if you know what kind of entries these are, give them a proper name!



          i think if you would have choosen a more compliant name (Log is really confusing) your idea would not have been so bad...






          share|improve this answer





















          • I beg to differ. 1) this isn't violated, it's still logging 2) OP added a profiler via their own extensions 3) it's not keeping any items but OP's extensions. The API might not be the prettiest one but in general there is nothing wrong with it. I use similar extensions myself. Lastly i think it is not a good idea of using KeyValue pairs this is also not true because you cannot know the names of the fields. A logger must be pretty flexible so using a dictionary was the right choice.
            – t3chb0t
            yesterday













          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f206860%2ffluent-interface-for-logger%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          -1














          i do not think this is really a good idea (sorry to say that)...



          why is is not a good idea? it's breaking the concept of segregaton of concerns:




          1. a Logger is responsible for logging

          2. a Profiler is responsible for measuring execution time

          3. a Logger is NOT responsible for keeping track of items (who is responsible for cleaning these entries?)


          another issue i see is that you create a new logger whenever you want to write something into you log, i don't see any reason for that...



          what would i suggest?



          create a timesheet



          public class Timesheet{

          private final Map<TimeStamp, KeyValue kv> entries;
          private final Logger logger;

          public Timesheet(Logger logger){
          this.logger = logger
          entries= ...
          }

          public Timesheet kv(Object key, Object value) {
          TimeStamp timestamp = new TimeStamp();
          entries.put(timestamp , new KeyValue(key, value));
          log.debug("adding key/value {}/{} at {}", key, value, timestamp );
          return this;
          }

          public Timesheet msg(Object msg) {
          logger.debug(msg);
          return this;
          }

          public Timesheet elapsed() {
          logger.debug("time elapsed {}", calculateTimeElapsed());
          return this;
          }

          }


          not all is implemented here, it should just girve you an idea of how you could do it...



          Timesheet timesheet = new Timesheet(LoggerFactory.getLogger("jsonLogger")); //now availible for all classes
          timesheet.msg("hello");
          timesheet.kv("foo", "bar");
          Thread.sleep(1234);
          timesheet.elapsed();


          some final words...



          i think it is not a good idea of using KeyValue pairs - if you know what kind of entries these are, give them a proper name!



          i think if you would have choosen a more compliant name (Log is really confusing) your idea would not have been so bad...






          share|improve this answer





















          • I beg to differ. 1) this isn't violated, it's still logging 2) OP added a profiler via their own extensions 3) it's not keeping any items but OP's extensions. The API might not be the prettiest one but in general there is nothing wrong with it. I use similar extensions myself. Lastly i think it is not a good idea of using KeyValue pairs this is also not true because you cannot know the names of the fields. A logger must be pretty flexible so using a dictionary was the right choice.
            – t3chb0t
            yesterday


















          -1














          i do not think this is really a good idea (sorry to say that)...



          why is is not a good idea? it's breaking the concept of segregaton of concerns:




          1. a Logger is responsible for logging

          2. a Profiler is responsible for measuring execution time

          3. a Logger is NOT responsible for keeping track of items (who is responsible for cleaning these entries?)


          another issue i see is that you create a new logger whenever you want to write something into you log, i don't see any reason for that...



          what would i suggest?



          create a timesheet



          public class Timesheet{

          private final Map<TimeStamp, KeyValue kv> entries;
          private final Logger logger;

          public Timesheet(Logger logger){
          this.logger = logger
          entries= ...
          }

          public Timesheet kv(Object key, Object value) {
          TimeStamp timestamp = new TimeStamp();
          entries.put(timestamp , new KeyValue(key, value));
          log.debug("adding key/value {}/{} at {}", key, value, timestamp );
          return this;
          }

          public Timesheet msg(Object msg) {
          logger.debug(msg);
          return this;
          }

          public Timesheet elapsed() {
          logger.debug("time elapsed {}", calculateTimeElapsed());
          return this;
          }

          }


          not all is implemented here, it should just girve you an idea of how you could do it...



          Timesheet timesheet = new Timesheet(LoggerFactory.getLogger("jsonLogger")); //now availible for all classes
          timesheet.msg("hello");
          timesheet.kv("foo", "bar");
          Thread.sleep(1234);
          timesheet.elapsed();


          some final words...



          i think it is not a good idea of using KeyValue pairs - if you know what kind of entries these are, give them a proper name!



          i think if you would have choosen a more compliant name (Log is really confusing) your idea would not have been so bad...






          share|improve this answer





















          • I beg to differ. 1) this isn't violated, it's still logging 2) OP added a profiler via their own extensions 3) it's not keeping any items but OP's extensions. The API might not be the prettiest one but in general there is nothing wrong with it. I use similar extensions myself. Lastly i think it is not a good idea of using KeyValue pairs this is also not true because you cannot know the names of the fields. A logger must be pretty flexible so using a dictionary was the right choice.
            – t3chb0t
            yesterday
















          -1












          -1








          -1






          i do not think this is really a good idea (sorry to say that)...



          why is is not a good idea? it's breaking the concept of segregaton of concerns:




          1. a Logger is responsible for logging

          2. a Profiler is responsible for measuring execution time

          3. a Logger is NOT responsible for keeping track of items (who is responsible for cleaning these entries?)


          another issue i see is that you create a new logger whenever you want to write something into you log, i don't see any reason for that...



          what would i suggest?



          create a timesheet



          public class Timesheet{

          private final Map<TimeStamp, KeyValue kv> entries;
          private final Logger logger;

          public Timesheet(Logger logger){
          this.logger = logger
          entries= ...
          }

          public Timesheet kv(Object key, Object value) {
          TimeStamp timestamp = new TimeStamp();
          entries.put(timestamp , new KeyValue(key, value));
          log.debug("adding key/value {}/{} at {}", key, value, timestamp );
          return this;
          }

          public Timesheet msg(Object msg) {
          logger.debug(msg);
          return this;
          }

          public Timesheet elapsed() {
          logger.debug("time elapsed {}", calculateTimeElapsed());
          return this;
          }

          }


          not all is implemented here, it should just girve you an idea of how you could do it...



          Timesheet timesheet = new Timesheet(LoggerFactory.getLogger("jsonLogger")); //now availible for all classes
          timesheet.msg("hello");
          timesheet.kv("foo", "bar");
          Thread.sleep(1234);
          timesheet.elapsed();


          some final words...



          i think it is not a good idea of using KeyValue pairs - if you know what kind of entries these are, give them a proper name!



          i think if you would have choosen a more compliant name (Log is really confusing) your idea would not have been so bad...






          share|improve this answer












          i do not think this is really a good idea (sorry to say that)...



          why is is not a good idea? it's breaking the concept of segregaton of concerns:




          1. a Logger is responsible for logging

          2. a Profiler is responsible for measuring execution time

          3. a Logger is NOT responsible for keeping track of items (who is responsible for cleaning these entries?)


          another issue i see is that you create a new logger whenever you want to write something into you log, i don't see any reason for that...



          what would i suggest?



          create a timesheet



          public class Timesheet{

          private final Map<TimeStamp, KeyValue kv> entries;
          private final Logger logger;

          public Timesheet(Logger logger){
          this.logger = logger
          entries= ...
          }

          public Timesheet kv(Object key, Object value) {
          TimeStamp timestamp = new TimeStamp();
          entries.put(timestamp , new KeyValue(key, value));
          log.debug("adding key/value {}/{} at {}", key, value, timestamp );
          return this;
          }

          public Timesheet msg(Object msg) {
          logger.debug(msg);
          return this;
          }

          public Timesheet elapsed() {
          logger.debug("time elapsed {}", calculateTimeElapsed());
          return this;
          }

          }


          not all is implemented here, it should just girve you an idea of how you could do it...



          Timesheet timesheet = new Timesheet(LoggerFactory.getLogger("jsonLogger")); //now availible for all classes
          timesheet.msg("hello");
          timesheet.kv("foo", "bar");
          Thread.sleep(1234);
          timesheet.elapsed();


          some final words...



          i think it is not a good idea of using KeyValue pairs - if you know what kind of entries these are, give them a proper name!



          i think if you would have choosen a more compliant name (Log is really confusing) your idea would not have been so bad...







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 '18 at 8:55









          Martin FrankMartin Frank

          545316




          545316












          • I beg to differ. 1) this isn't violated, it's still logging 2) OP added a profiler via their own extensions 3) it's not keeping any items but OP's extensions. The API might not be the prettiest one but in general there is nothing wrong with it. I use similar extensions myself. Lastly i think it is not a good idea of using KeyValue pairs this is also not true because you cannot know the names of the fields. A logger must be pretty flexible so using a dictionary was the right choice.
            – t3chb0t
            yesterday




















          • I beg to differ. 1) this isn't violated, it's still logging 2) OP added a profiler via their own extensions 3) it's not keeping any items but OP's extensions. The API might not be the prettiest one but in general there is nothing wrong with it. I use similar extensions myself. Lastly i think it is not a good idea of using KeyValue pairs this is also not true because you cannot know the names of the fields. A logger must be pretty flexible so using a dictionary was the right choice.
            – t3chb0t
            yesterday


















          I beg to differ. 1) this isn't violated, it's still logging 2) OP added a profiler via their own extensions 3) it's not keeping any items but OP's extensions. The API might not be the prettiest one but in general there is nothing wrong with it. I use similar extensions myself. Lastly i think it is not a good idea of using KeyValue pairs this is also not true because you cannot know the names of the fields. A logger must be pretty flexible so using a dictionary was the right choice.
          – t3chb0t
          yesterday






          I beg to differ. 1) this isn't violated, it's still logging 2) OP added a profiler via their own extensions 3) it's not keeping any items but OP's extensions. The API might not be the prettiest one but in general there is nothing wrong with it. I use similar extensions myself. Lastly i think it is not a good idea of using KeyValue pairs this is also not true because you cannot know the names of the fields. A logger must be pretty flexible so using a dictionary was the right choice.
          – t3chb0t
          yesterday




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f206860%2ffluent-interface-for-logger%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to reconfigure Docker Trusted Registry 2.x.x to use CEPH FS mount instead of NFS and other traditional...

          is 'sed' thread safe

          How to make a Squid Proxy server?