Fluent interface for Logger
up vote
0
down vote
favorite
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
add a comment |
up vote
0
down vote
favorite
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
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
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
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
java logging fluent-interface logback
edited Nov 4 at 10:00
t3chb0t
33.8k746111
33.8k746111
asked Nov 3 at 9:56
Enrichman
1213
1213
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
up vote
0
down vote
If you're using SLF4J API, which is what it looks like you're using, I would recommend a slightly different approach.
To start, I believe you would be better off extending the Logger class. This would be beneficial because you would inherit the classes provided and can override the necessary classes.
Usually in Java when we are creating helper classes, we override the base class and then write whatever code we would like to supplement the already existing functionality.
Also, in the future please note that you should explain what you've written a bit more in the question, so that reviewers have an easier time understanding your code and thus can better help suggest improvements.
I hope this feedback helps you improve your code. If you have any questions, feel free to leave a comment.
add a comment |
up vote
0
down vote
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:
- a Logger is responsible for logging
- a Profiler is responsible for measuring execution time
- 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...
add a comment |
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',
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
If you're using SLF4J API, which is what it looks like you're using, I would recommend a slightly different approach.
To start, I believe you would be better off extending the Logger class. This would be beneficial because you would inherit the classes provided and can override the necessary classes.
Usually in Java when we are creating helper classes, we override the base class and then write whatever code we would like to supplement the already existing functionality.
Also, in the future please note that you should explain what you've written a bit more in the question, so that reviewers have an easier time understanding your code and thus can better help suggest improvements.
I hope this feedback helps you improve your code. If you have any questions, feel free to leave a comment.
add a comment |
up vote
0
down vote
If you're using SLF4J API, which is what it looks like you're using, I would recommend a slightly different approach.
To start, I believe you would be better off extending the Logger class. This would be beneficial because you would inherit the classes provided and can override the necessary classes.
Usually in Java when we are creating helper classes, we override the base class and then write whatever code we would like to supplement the already existing functionality.
Also, in the future please note that you should explain what you've written a bit more in the question, so that reviewers have an easier time understanding your code and thus can better help suggest improvements.
I hope this feedback helps you improve your code. If you have any questions, feel free to leave a comment.
add a comment |
up vote
0
down vote
up vote
0
down vote
If you're using SLF4J API, which is what it looks like you're using, I would recommend a slightly different approach.
To start, I believe you would be better off extending the Logger class. This would be beneficial because you would inherit the classes provided and can override the necessary classes.
Usually in Java when we are creating helper classes, we override the base class and then write whatever code we would like to supplement the already existing functionality.
Also, in the future please note that you should explain what you've written a bit more in the question, so that reviewers have an easier time understanding your code and thus can better help suggest improvements.
I hope this feedback helps you improve your code. If you have any questions, feel free to leave a comment.
If you're using SLF4J API, which is what it looks like you're using, I would recommend a slightly different approach.
To start, I believe you would be better off extending the Logger class. This would be beneficial because you would inherit the classes provided and can override the necessary classes.
Usually in Java when we are creating helper classes, we override the base class and then write whatever code we would like to supplement the already existing functionality.
Also, in the future please note that you should explain what you've written a bit more in the question, so that reviewers have an easier time understanding your code and thus can better help suggest improvements.
I hope this feedback helps you improve your code. If you have any questions, feel free to leave a comment.
answered Nov 4 at 6:57
Faraz
270110
270110
add a comment |
add a comment |
up vote
0
down vote
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:
- a Logger is responsible for logging
- a Profiler is responsible for measuring execution time
- 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...
add a comment |
up vote
0
down vote
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:
- a Logger is responsible for logging
- a Profiler is responsible for measuring execution time
- 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...
add a comment |
up vote
0
down vote
up vote
0
down vote
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:
- a Logger is responsible for logging
- a Profiler is responsible for measuring execution time
- 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...
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:
- a Logger is responsible for logging
- a Profiler is responsible for measuring execution time
- 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...
answered Nov 8 at 8:55
Martin Frank
547316
547316
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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