I am trying to learn the trick on how to run the code which prints a lot of stuff when the debug flag is on.
How is that done in java.
A very naive way I can think of is have the debug flag in all the methods i write
and write something like
if (this.debug == true){
System.out.println("blah blah");
}
But there should be much more elegant way rather than having all these ifs in code?
Also, is there a way I can get the line number of certain execution in code:
For example if there is an exception
try:
/* line number 22 */
catch Exception e{
//print that exception occured in above line number??
}
Probably very lame questions.
THanks
Use logging framework that will do it for you - for example : log4j, slf4j
For example:
log.debug("some text");
now in logging configuration properties file choose to enable disabled debug logging statements
See
log4j manual
slf4j
Simple example from log4j API
private Logger _debugLogger = Logger.getLogger(yourClassName.class);
//For info mode
_debugLogger.info("Some Messages");
//or for debug mode
_debugLogger.debug(MessageFormat.format("Some message {0},{1},{2}",variable0, variable1,variable2));
Related
First of all, Java is not my usual language, so I'm quite basic at it. I need to use it for this particular project, so please be patient, and if I have omitted any relevant information, please ask for it, I will be happy to provide it.
I have been able to implement coreNLP, and, seemingly, have it working right, but is generating lots of messages like:
ene 20, 2017 10:38:42 AM edu.stanford.nlp.process.PTBLexer next
ADVERTENCIA: Untokenizable: 【 (U+3010, decimal: 12304)
After some research (documentation, google, other threads here), I think (sorry, I don't know how I can tell for sure) coreNLP is finding the slf4j-api.jar in my classpath, and logging through it.
Which properties of the JVM can I use to set logging level of the messages that will be printed out?
Also, in which .properties file I could set them? (I already have a commons-logging.properties, a simplelog.properties and a StanfordCoreNLP.properties in my project's resource folder to set properties for other packages).
Om’s answer is good, but two other possibly useful approaches:
If it is just these warnings from the tokenizer that are annoying you, you can (in code or in StanfordCoreNLP.properties) set a property so they disappear: props.setProperty("tokenize.options", "untokenizable=NoneKeep");.
If slf4j is on the classpath, then, by default, our own Redwoods logger will indeed log through slf4j. So, you can also set the logging level using slf4j.
If I understand your problem, you want to disable all StanfordNLP logging message while the program is executing.
You can disable the logging message. Redwood logging framework is used as logging framework in Stanford NLP. First, clear the Redwood's default configuration(to display log message) then create StanfordNLP pipeline.
import edu.stanford.nlp.util.logging.RedwoodConfiguration;
RedwoodConfiguration.current().clear().apply();
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Hope it helps.
In accordance with Christopher Manning's suggestion, I followed this link
How to configure slf4j-simple
I created a file src/simplelogger.properties with the line org.slf4j.simpleLogger.defaultLogLevel=warn.
I am able to solve it by setting a blank output stream to system error stream.
System.setErr(new PrintStream(new BlankOutputStream())); // set blank error stream
// ... Add annotators ...
System.setErr(System.err); // Reset to default
Accompanying class is
public class BlankOutputStream extends OutputStream {
#Override
public void write(int b) throws IOException {
// Do nothing
}
}
Om's answer disables all logging. However, if you wish to still log errors then use:
RedwoodConfiguration.errorLevel().apply();
I also use jdk logging instead of slf4j logging to avoid loading slfj dependencies as follows:
RedwoodConfiguration.javaUtilLogging().apply();
Both options can be used together and in any order. Required import is:
import edu.stanford.nlp.util.logging.RedwoodConfiguration;
We are maintaining two different log files, one to log only error messages, and other for debug information. I don't want to clutter the error file with exception stack trace, so I have to add following two lines each time on catching any exception
try{
...
}
catch(Exception e){
log.error("Error during SOME_SERVICE {}" , e.getMessage());
log.debug("Exception ", e);
}
Is there any simpler way to do this, may be in a single line of code?
As suggested in the comments, I have two options, either live with it, or write my own custom logger that would do the expected behavior. For now, I leave it as is.
For custom logging there are tons of resources, so won't post the solution here.
Implement Custom Logger with slf4j
I am trying to use LoggerHandler to log all incoming requests. I am using logback.xml to specify appenders. I am setting system property for logging.
System.setProperty("org.vertx.logger-delegate-factory-class-name",
"org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");
Still it is logging everything in console not in file.
This worked for me with Vert.x 3.4.1:
import static io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME;
import io.vertx.core.logging.LoggerFactory;
// ...
setProperty (LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory.class.getName ());
LoggerFactory.getLogger (LoggerFactory.class); // Required for Logback to work in Vertx
The key is to get a logger, which I guess initializes the Logging subsystem, the class that you use to get a Logger seems irrelevant as I tried with two different ones.
I run these lines as the first ones of the program in production code and in the tests to work properly in both contexts.
I was able to get it to work by setting the VM options as such:
-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.Log4jLogDelegateFactory
Then in my log4j.properties, I had to add this:
log4j.category.io.vertx = TRACE
I know this question is getting a bit old, but the only way I was able to get the vertx LoggerHandler to not use JUL was to call LoggerFactory.initialise() after setting the system property as described in the question.
Even better, I set the property in my build.gradle, like so:
run {
systemProperty(
"vertx.logger-delegate-factory-class-name",
"io.vertx.core.logging.SLF4JLogDelegateFactory"
)
args = ['run', mainVerticleName, "--redeploy=$watchForChange", "--launcher-class=$mainClassName", "--on-redeploy=$doOnChange",
"-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.SLF4JLogDelegateFactory" ]
}
And then at the very top of my MainVerticle::start I have:
LoggerFactory.initialise()
And, boom. Everything is now formatted correctly, including all the startup output.
My Program not error is perfect work but I feel annoyed from warning message.
So, I want to hide it from program console. What should I do?
(i can't edit html source code)
[Thread-4] WARN jodd.lagarto.dom.LagartoDOMBuilderTagVisitor - Orphan closed tag ignored </meta>
[Thread-3] WARN jodd.lagarto.dom.LagartoDOMBuilderTagVisitor - Unclosed tag closed: <p>
Thanks for kindness.
Oh Yea!
I can find solution with myself. (Thank a lot Elliott Frisch for guide :) )
i use Logback Library
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
public class Main {
final static Logger joddlogger = (Logger) LoggerFactory.getLogger("jodd");
public static void main(String[] argv) {
joddlogger.setLevel(ch.qos.logback.classic.Level.OFF);
//do something...
}
}
That is one correct answer, as #Jaynova and #Elliott Frisch said. Jodd uses Logback, so all you have to do is to mute the logging category in logback configuration, as explained in the other answer. You can do that from Java or from logback configuration file.
There is one more solution, added recently: LagartoDOMBuilder has a property parsingErrorLogLevel, which purpose is to set the log level of parsing errors (by default is set to WARN). Sometimes, its important to have these errors in the log (eg parsing your own code), and sometimes its just annoying (parsing live code, usually with lot of errors).
So while you can switch off the all logging for that package, you may also mute just the parsing errors by setting the level to DEBUG (assuming your global log level is higher).
So, in short, get the LagartoDOMBuilder instance before parsing and set this flag :)
What is the difference between logger.debug and logger.info ?
When will logger.debug be printed?
I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.
The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception, you might call Logger.error. If you want to print the value of a variable at any given point, you might call Logger.debug. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.
In the case of log4j at least, the ordering of log levels is:
DEBUG < INFO < WARN < ERROR < FATAL
Here is a short example from that article demonstrating how log levels work.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
// This request is enabled, because WARN >= INFO.
logger.warn("Low fuel level.");
// This request is disabled, because DEBUG < INFO.
logger.debug("Starting search for nearest gas station.");
// The logger instance barlogger, named "com.foo.Bar",
// will inherit its level from the logger named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barlogger.info("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO.
barlogger.debug("Exiting gas station search");
This will depend on the logging configuration. The default value will depend on the framework being used. The idea is that later on by changing a configuration setting from INFO to DEBUG you will see a ton of more (or less if the other way around) lines printed without recompiling the whole application.
If you think which one to use then it boils down to thinking what you want to see on which level. For other levels for example in Log4J look at the API, http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Level.html
Just a clarification about the set of all possible levels, that are:
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
Basically it depends on how your loggers are configured. Typically you'd have debug output written out during development but turned off in production - or possibly have selected debug categories writing out while debugging a particular area.
The point of having different priorities is to allow you to turn up/down the level of detail on a particular component in a reasonably fine-grained way - and only needing to change the logging configuration (rather than code) to see the difference.
INFO is used to log the information your program is working as expected.
DEBUG is used to find the reason in case your program is not working as expected or an exception has occurred. it's in the interest of the developer.
This is a very old question, but i don't see my understanding here so I will add my 2 cents:
Every level corresponds/maps to a type of user:
debug : developer - manual debugging
trace : automated logging and step tracer - for 3rd level support
info : technician / support level 1 /2
warn : technician / user error : automated alert / support level 1
critical/fatal : depends on your setup - local IT
It depends on which level you selected in your log4j configuration file.
<Loggers>
<Root level="info">
...
If your level is "info" (by default), logger.debug(...) will not be printed in your console.
However, if your level is "debug", it will.
Depending on the criticality level of your code, you should use the most accurate level among the following ones :
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
Info Messages are something which we would like to see even if the application is in best of state.
Debug messages are usually something that we would like to see while debugging some problem.
What is the difference between logger.debug and logger.info?
These are only some default level already defined. You can define your own levels if you like.
The purpose of those levels is to enable/disable one or more of them, without making any change in your code.
When logger.debug will be printed ??
When you have enabled the debug or any higher level in your configuration.