By default slf4j, when using with jdk (slf4j-jdk14-1.6.1.jar), does not log debug messages.
How do I enable them?
I can’t find info neither in the official docs, the web or here on how to enable it.
I found some info on (failed though) creating a file in %JDK_HOME%/lib and defining the level there, in a config file.
However, I would like to define the level at compile-/run-time so I can both run and debug my app from my IDE with different logging levels.
Isn’t there some environment variable I can set, or VM arg?
Why do you think it does not log DEBUG messages?
If you mean that your log.debug(String) logging calls do not end up in java.util.logging log files, then I guess you have to configure the logging.properties configuration file to allow log messages at FINE level.
If you do not want to mess with the global %JRE_HOME%/lib/logging.properties, then you can just pass in -Djava.util.logging.config.file=logging.properties on the command line - this will force the logging system to look for that configuration file in the current directory.
Or use some other (programmatic) way to configure java.util.logging, see below for tutorial.
This has nothing to do with configuring SLF4J; in fact, SLF4J does not have any configuration, everything is configured by simply swapping JAR files.
For your reference:
JDK14LoggerAdapter
Java Logging API tutorial
If you are using slf4j SimpleLogger implementation read this.
There you can see that simpleLogger use INFO as default log level. You can change it by using a system property. This is usefull for non-production evironments:
static {
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
}
You can add -Dorg.slf4j.simpleLogger.defaultLogLevel=debug to the VM options.
I just put my logging.properties file in my applications WEB-INF/classes file (or use the command line argument identified by Neeme Praks if you're not deploying in a war), and have the properties file open in eclipse so I can fine tune it to log the packages and at the level I'm interested in.
In the logging.properties file, you need to make sure that both the logger level and the handler level are set to the level you want. For example, if you want your output to go to the console, you need to have at least the following:
#logging.properties file contents
#Define handlers
handlers=java.util.logging.ConsoleHandler
#Set handler log level
java.util.logging.ConsoleHandler.level=FINE
#Define your logger level
com.company.application.package.package.level=FINE
#Assign your handler to your logger
com.company.application.package.package.handlers=java.util.logging.ConsoleHandler
You mentioned the slf4j-jdk14-1.6.1.jar. This provides the slf4j binding to java.util.logging. You need to have that in your classpath, but make sure you also have the slf4j api (slf4j-api-1.7.12.jar) in your classpath as well.
I find the example logging.properties file in this link useful for creating a variety of loggers and handlers, to give you fine-grained control over what logs go to the console, and what logs go to a file:.
And here's the slf4j manual.
if you are using lombok Slf4j
package com.space.slf4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* #author anson
* #date 2019/6/18 16:17
*/
#Slf4j
#RestController
public class TestController {
#RequestMapping("/log")
public String testLog(){
log.info("######### info #########");
log.debug("######### debug #########");
log.error("######### error #########");
return null;
}
}
application.yml
logging:
level:
root: debug
In runtime with the default configuration you can enable it with this code:
public class MyTest {
static {
Logger rootLogger = Logger.getLogger("");
rootLogger.setLevel(Level.ALL);
rootLogger.getHandlers()[0].setLevel(Level.ALL);
}
I'm using this code inside TestNG Unit.
Related
I am using Apache Commons Logging ™. For now I wanted to use SimpleLog implementation, but when I changed the level, loggers from the libraries came out. I want it to turn them off.
Is there a easy way to change log level for whole package (can Log4j do that)?
I have tried to set
org.apache.commons.logging.simplelog.log.foo=fatal
in the property files to disable (setting to fatal is OK) foo logger, but it doesn't work (foo is a name of logger that appears in output : [INFO] foo - Message).
In Log4j you can specify a logging level for specified package, class or logger identified by string. You just simply write this in log4j.properties file:
log4j.logger.<your package> = DEBUG|INFO|OFF|WARN...
You should use:
log4j.logger.foo = OFF
Please note that "foo" does not need to be a package, or a class, but is an arbitrary String. We e.g. have a logger named "SQL" that is called from many classes.
If you use Spring Boot, you may set to OFF in application.properties file, by using logging.level.<package-or-class-name>=OFF Example:
logging.level.org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer=OFF
Reference:
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.logging.log-levels
Use of SimpleLog from Commons Logging requires two configuration files unless you are using some system properties. The files are: commons-logging.properties and simplelog.properties.
The log level properties you have indicated should be placed in simplelog.properties like:
org.apache.commons.logging.simplelog.log.foo=warn
where "foo" is the logger name. Generally, this is the package or package and class name. In the following example, everything under the com.stackoverflow.utils package is set to info whereas com.stackoverflow.servlet.Dispatcher is specifically set to warn:
org.apache.commons.logging.simplelog.log.com.stackoverflow.utils=info
org.apache.commons.logging.simplelog.log.com.stackoverflow.servlet.Dispatcher=warn
The commons-logging.properties file should contain:
org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
Documentation here and here.
I'm having some trouble configuring proper logging in Eclipse Scout framework. My claims aren't that high as I only want to be able to set different log levels for different parts of my program in a configuration/properties/XML file.
The logging configuration in the config.ini of my Scout server plugin currently looks like this:
eclipse.consoleLog=true
org.eclipse.scout.log=eclipse
org.eclipse.scout.log.level=INFO
So as you can see this is the default logging configuration using Eclipse logging. It works fine for logging at a global level. The only thing I would like to do is to write something like this to set the different log levels:
packagename.ClassName=LOGLEVEL
As this is a very basic logging use case I think there must be some easy way to do this in Scout. Otherwise I would appreciate some help how to configure log4j, JUL or others for the use with Scout. The Eclipse Scout Wiki hasn't helped me so far. I created the example logger fragment to the host plugin 'org.eclipse.scout.commons' and removed the logging configuration lines from my config.ini but nothing happens. I'm also not sure where to put the log4j.poperties or how this is done otherwise.
I'm a bit ashamed for being unable to figure out such a basic problem, but would be very happy about some quick help.
I can tell you how to configure the logging if you choose the java logger (config.ini: org.eclipse.scout.log=java).
For the eclipse logger, I barely found any information at all.
Now, to configure the java (JUL) logging: You can do this in a file called logging.properties.
You can configure the logging by specifying the configuration file in your product:
Create your configuration file - say logging.properties inside the folder where your product file (for server or client respectively) is located. Typically this is in a folder named 'products'.
Open your product file and go to the "Launching" tab and specify your logging configuration file in the "VM Arguments" tab. Use the "java.util.logging.config.file" system property to do so:
-Djava.util.logging.config.file="${resource_loc:/com.yourapp.server/products/logging.properties}"
Now, you should be able to specify the log levels in your new logging.properties file:
### Root level of your application, all below are ignored
.level=INFO
### Handlers
handlers=java.util.logging.ConsoleHandler
### Handler properties
java.util.logging.ConsoleHandler.level=FINEST
### Override the logging level for certain classes
com.yourapp.server.SomeService.level=FINE
Alternatively, you can also use a class to initialize the logging with the java.util.logging.config.class option. See this wiki page for a detailed example.
Also, when building a WAR file, you might be interested in this answer.
The application I am working with has log calls in the catch blocks auto-generated by NetBeans only and no other kind of logging:
Logger.getLogger(SomeClass.class.getName()).log(Level.SEVERE, null, ex);
What steps should be taken to redirect log output from the console to for example a text file?
I read Lars Vogel tutoriral http://www.vogella.com/tutorials/Logging/article.html and for the most part understand what he is doing, but apparently when he wanted to log an event, he would call a method from an instance of his own logger LOGGER.
NetBeans developers probably intended to auto-generate the log calls the way they did for a reason. Does their logging have to be replaced as in the tutorial, or can it be simply configured to use another logging destination?
My confusion stems from the fact that Logger.getLogger is a static method.
What steps should be taken to redirect log output from the console to for example a text file?
From the Java Logging Overview Examples:
public static void main(String[] args) {
Handler fh = new FileHandler("%t/wombat.log");
Logger.getLogger("").addHandler(fh);
Logger.getLogger("com.wombat").setLevel(Level.FINEST);
...
}
That example creates a wombat.log file in the temp directory.
Otherwise you can modify or specify a logging.properties entry to install a FileHandler. Here is a modified entry of the 'lib/logging.properties' located in your Java Home directory.
############################################################
# Global properties
############################################################
# "handlers" specifies a comma separated list of log Handler
# classes. These handlers will be installed during VM startup.
# Note that these classes must be on the system classpath.
# By default we only configure a ConsoleHandler, which will only
# show messages at the INFO and above levels.
#
#handlers= java.util.logging.ConsoleHandler
# To also add the FileHandler, use the following line instead.
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler
You can use the 'java.util.logging.config.file' system property on launch to specify alternate log configuration files.
if getLogger() is a static method, which executes without an instance of Logger class being created,
Contained in the Java Logging Overview listed above there is a link to the Java SE API Specification. That is the contract for how all this works.
If you look up Logger.getLogger you'll see:
Find or create a logger for a named subsystem. If a logger has already been created with the given name it is returned. Otherwise a new logger is created.
If a new logger is created its log level will be configured based on the LogManager configuration and it will configured to also send logging output to its parent's Handlers. It will be registered in the LogManager global namespace.
The getLogger method is creating or locating a logger.
than where does addHandler() persist its result?
Handlers are store on the logger instance. The output type depends on the handler. The properties of each handler are described in the API spec.
The Logging Hierarchy and Record Forwarding might help you understand what is happening in the example code.
log4j has a property, log4j.debug, which will helpfully provide the user with an indication of which configuration file was actually used to configure the logging system.
I haven't been able to find anything equivalent with the (otherwise superior) Logback logging framework. Is there any way to print (for diagnostic purposes) at runtime, which configuration file Logback used to bootstrap itself?
[edit]
To clarify, I'd ideally like a solution that doesn't require me to modify the configuration file itself (since a badly assembled third-party JAR, for example, may be picked up incorrectly, and prior to my logback configuration XML).
You can set a Java system property to output Logback debugging info:
java -Dlogback.statusListenerClass=ch.qos.logback.core.status.OnConsoleStatusListener
This is further explained by the Logback documentation for automatic status printing (very bottom mentions forcing status output) and the logback.statusListenerClass property:
In the absence of status messages, tracking down a rogue logback.xml configuration file can be difficult, especially in production where the application source cannot be easily modified. To help identify the location of a rogue configuration file, you can set a StatusListener via the "logback.statusListenerClass" system property (defined below) to force output of status messages. The "logback.statusListenerClass" system property can also be used to silence output automatically generated in case of errors.
If you want to go deep into Logback, you can do the following
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.joran.util.ConfigurationWatchListUtil;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
LoggerContext loggerContext = ((ch.qos.logback.classic.Logger)logger).getLoggerContext();
URL mainURL = ConfigurationWatchListUtil.getMainWatchURL(loggerContext);
System.out.println(mainURL);
// or even
logger.info("Logback used '{}' as the configuration file.", mainURL);
}
}
It will print the URL of the loaded configuration file.
you can set debug="true" in a logback.xml file that you control like this:
<configuration debug="true">
(...)
</configuration
and tho make sure that file is going to be used by logback add following VM argument when you start your program:
-Dlogback.configurationFile=/path/to/yourlogback.xml
This does not really answer to your question but gives you a work around solution.
Not very scientific, but it works if you just want a quick confirmation.
I simply changed the log entry pattern and observed whether or not it changed in my console/log file.
I have the following log4j.properties file, for an application deployed in WebSphere Portal:
log4j.rootLogger=DEBUG, InfoAppender, DebugAppender
log4j.appender.InfoAppender=org.apache.log4j.RollingFileAppender
log4j.appender.InfoAppender.Threshold=INFO
log4j.appender.InfoAppender.File=C:/info.log
log4j.appender.InfoAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.InfoAppender.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.DebugAppender=org.apache.log4j.RollingFileAppender
log4j.appender.DebugAppender.Threshold=DEBUG
log4j.appender.DebugAppender.File=C:/debug.log
log4j.appender.DebugAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.DebugAppender.layout.ConversionPattern=%d %p [%c] - %m%n
When I code, I define the logger at class level:
private static Logger logger = Logger.getLogger(IWannaLogThis.class);
And I log INFO messages with this:
logger.info(theObjectToLog);
When I deploy my application, the debug.log file gets everything I log with logger.debug() but ignores everything I write with logger.info(). On the other side, the info.log file keeps empty.
The weirdest thing is that in debug.log and info.log appears some INFO and DEBUG messages made by some JARS (like Hibernate Validator) I had in the classpath, but just ignores everything I try to log in my code.
Any ideas?
This is most likely a classloading-related problem. WebSphere Portal uses Log4J internally, so I'm guessing that you end up using WebSphere Portal's provided Log4J JAR file as well as its own Log4J properties.
You can verify that by adding the following to the JVM arguments of the server instance:
-Dlog4j.debug=true
And then inspect the SystemOut.log file. Log4J will spit out lots of tracing information about the configuration file(s) it reads.
The best way to avoid this is to do the following:
Bundle the Log4J JAR file with your application.
Associate a Shared Library with the server. In that Shared Library, place your Log4J configuration file.
As an alternative to step 2, you can bundle your Log4J configuration file with the application itself, however that would carry its own drawbacks (for example, having to repackage your application whenever you perform a Log4J configuration change).
Another common problem is that the JARs you have in your classpath also use log4j and also have their own appenders set. So depending on the settings that they use, and the packages that your classes reside in, this may lead to the problem you describe.
So:
Make sure that your package names are unique and not used by any of the third party libraries.
Check the log4j settings in all libraries in your classpath. They should not contain general settings which override yours.
Make sure your loggers use your log4j.properties (you can be sure if changes you make in your file affect your loggers as expected).
If you can, make sure that your log4j stuff loads last, in case any of the third party libs reset the configuration. They shouldn't, but who can stop them.
Normally, it should be one of these things. Post more explicit example if it doesn't work.
Good luck!
What I have done in the past is set specific logs for the classes I want to log. It sounds like you can try setting your root logger to INFO and see if that gets you the messages you want. Here's a little bit of my log4j property file. I set a logger for each class and assign it to my "data" appender, which defines the log layout. In the loggers I specify specific classes I want to log and set their Log level individually. Any class that logs that is not defined in the Loggers I have use the default log level for the rootCategory.
log4j.rootCategory=INFO, rollingFile, stdout
#GetData Loggers
log4j.logger.com.myapp.data=INFO, data
log4j.logger.com.myapp.data.SybaseConnection=DEBUG, data
log4j.logger.com.myapp.data.GetData=ERROR, data
# data appender
log4j.appender.data=org.apache.log4j.RollingFileAppender
log4j.appender.data.layout=org.apache.log4j.PatternLayout
log4j.appender.data.File=c\:\\Program Files\\MyApp\\logs\\MyApp-data.log
log4j.appender.data.Append=true
log4j.appender.data.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
you root logger opens the log properties in the debug mode,
use INFO instead of DEbug in the first line of your properties file.