Java logging all except one - java

I have the following logging.properties file:
handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.FileHandler.pattern = /tmp/file.log
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.append = true
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$td.%1$tm.%1$tY %1$tH:%1$tM:%1$tS [%4$s] %5$s%6$s%n
fileclass = INFO, FileHandler
Currently everything goes to the console, plus 'fileclass' package into the file,
but I want 'fileclass' package to be excluded from the console.
I could define main package to go to the console, but the main program doesnt
have the package.
Is it possible to have such case within logging.properties:
- Everything goes to the console, except 'fileclass' which goes to the file

I haven't used Java Util Logger but normally that's related to "Additivity" of logger.
The way to achieve what you want is, set additivity of fileclass logger to false (which means excluding usage of parent appenders/handlers. Then add only the appender/handler you want for fileclass
The way to control additivity in Java Util Logging is by using useParentHandlers in your config. So it looks like:
fileclass.useParentHandlers=false
fileclass = INFO, FileHandler
By doing so, fileclass logger is not going to inherit handlers of its parent, and only use whatever you set to it.
One thing to note is, because logger is hierarchical. Therefore it will affect fileclass logger and all its children logger. For example if you have a logger called fileclass.foo, it will also be using only the FileHandler, which may or may not be what you want.

This can be done a couple ways.
Let's assume you want to leave the default console handler.
You can remove java.util.logging.FileHandler from the global handlers list, thus leaving you with the following:
handlers=java.util.logging.ConsoleHandler
This will cause all applications to log to the console. To complete your case, we must ensure 'fileclass' does not log to the console, yet does log to a file.
You can do this programmatically or declaratively:
Programmatically
Within the 'fileclass' app. Create a custom logger.
e.g.
Logger logger = Logger.getLogger(FileClass.class.getName());
// set logger level
logger.setLevel(Level.INFO);
FileHandler fileHandler = new FileHandler("file.log");
// Set the handler level
// NOTE: This setting will ignore INFO records sent by the logger
fileHandler.setLevel(Level.WARNING);
logger.addHandler(fileHandler);
Now that you've added a FileHandler manually. All that is left to do is disconnect the java.util.logging.ConsoleHandler from your 'fileclass'. You can do this by calling logger.removeHandler(consoleHandler), where consoleHandler is the instance of java.util.logging.ConsoleHandler
Declaratively
You can also declaratively add a file handler and disable parents and global handlers
# disable parents, e.g. in this case the console handler
com.some.package.useParentHandlers=false
# add the file handler
com.some.package.logger.MyLogger.level=INFO
com.some.package.MyFileHandler.pattern=%h/CoolLog%g.log
com.some.package.handler.MyFileHandler.limit=20000000
com.some.package.handler.MyFileHandler.count=20
This will enable you add add a file handle specifically for that application, however it won't remove the console handler since its declared globally.
You may want to take a look at my blog posts on Java Logging:
understand java logging
progammatically overriding logging.properties

Related

How do I change a remote application's logback log level through http (rest)?

How do I change a remote application's logback log level through http (rest)? to
#Controller
public class ChangeLog2Controller {
#PostMapping("/api/testlog1")
public ResponseModel testLogeBack(#RequestBody LogLevelModel levelModel) {
...
}
}
Something like this ...
#PostMapping("/api/testlog1")
public ResponseModel testLogeBack(#RequestBody LogLevelModel levelModel) {
// change the log level for the root logger
Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(...);
// change the log level for a specific logger
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger specificLogger = loggerContext.getLogger("com.some.specific.package");
specificLogger.setLevel(...);
}
... where the parameter passed into setLevel() is something like Level.INFO which would, I presume, be derived from your LogLevelModel.
Note: if you are looking for some way to dynamically change logging configuration and a JMX client (rather than a HTTP client) would suffice then Logback already provides a JMX Configurator which yuou can engage by simply adding the following to your logback.xml: <jmxConfigurator />. This exposes a JMX MBean which you can use to view and set log levels.
Edit 1: based on the comments below it seems like your requirement might be to invoke WebApplicationA and somehow enable WebApplicationA to change the log level for loggers inside WebApplicationB? If so, then either
WebApplicationA has to use the JMXConfigurator MBean exposed by WebApplicationB. There are examples of Java JMX clients here and here. However, in order to expose the JMXConfigurator you must have some control over WebApplicationB's logback.xml and, if so, then perhaps you also have some control over WebApplicationB's implementation in which case it might be easier to just expose a simple setLogLevel REST endpoint in WebApplicationB and let WebApplicationA invoke that rather than playing around with a Java JMX client.
Or
WebApplicationB has to expose a changeLogLevel REST API (with an implementation like the one I provided above) which WebApplicationA can invoke.
The only other alternative is that WebApplicationA somehow changes the logback.xml used by WebApplicationB and WebApplicationB's logback.xml starts looks like this ...
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
... so that any changes made to this file on WebApplicationB's classpath are picked up within (for example) 30 seconds. But, since WebApplicationB's logback.xml is likely to be embedded in a WAR (or similar) this approach seems very awkward and very likely undesireable.

check enable of logger level vs don't check in SLF4J\Logback

I using SLF4J and Logback for logging infrastructure at my application.
I using Logger.isDebugEnable() method before any log, for sample:
if(logger.isDebugEnable())
logger.debug('process transaction....')
goal of above code is : don't construct string process transaction.... in heap when log level is not Debug.
My question is:
Is there benefit between my code style or direct logger.debug('process transaction....') without check enable log level?
This is a legacy from the log4j project. slf4j has introduced the {} construction which allow you to use:
logger.debug("{}: {}", "MyClass", "Message to show to user");
where the logger backend first checks for "is...Enabled()" and then constructs the logger string.
As the backend checks itself you do not need to, and the if clause can be removed leaving only the logger statement itself.

Logger not functioning properly

I am using java.util.logging.Logger Class for logging in my application. I have added FileHandler so that the application log is stored directly in log.txt file.
But for some reason, after the application is terminated the log is far from complete. On cmd, I can see all the statements but they are never appended to the file.
I have set FileHandler to the Logger by:
private void setLogger() {
try {
FileHandler hand = new FileHandler("log/log.txt", true);
hand.setFormatter(new SimpleFormatter());
Logger log = Logger.getLogger(ImageRename.MAIN_LOG);
//log.setUseParentHandlers(false);
log.addHandler(hand);
log.setLevel(Level.ALL);
} catch (IOException e) {
System.out.println("Could Not set logger");
}
}
Any problem with flushing? How to solve it? Thanks.
PS: On debugging, I have noticed that in between
Logger.getLogger(ImageRename.MAIN_LOG).getHandlers().length
returns 0. Where as it should return 1. Initially it was printing 1, but somewhere down the line it becomes zero.
The problem is ... garbage collection.
What is happening is likely the following:
You call Logger.getLogger(ImageRename.MAIN_LOG);
You setup the logger.
Java notices it is unreferenced, and discards it.
You call Logger.getLogger(ImageRename.MAIN_LOG); and expect to get the same logger.
A fresh logger is set up with default configuration.
You can avoid this by two measures:
Use a configuration file logging.properties for configuration. When creating the logger, the Java logging API will consult the configuration, and thus recreate it appropriately.
Use static references. This is a best practise anyway. Equip each class with a logger:
private final static Logger LOG =
Logger.getLogger(ExampleClass.class.getName());
While the class is loaded it then should not be garbage collected AFAICT.
See e.g. http://www.massapi.com/class/fi/FileHandler.html for an example (found via Google)
Note the following line, which may be your problem:
fileHandler.setLevel(Level.ALL);
(Note: this is the level of the Handler, not of the Logger or message.)
For debugging, first try to get messages at an ERROR level logged. Messages at level INFO and below are often supressed by default.
Also try setting the logging level as soon as possible. In my experience, the most reliable way of configuring Java logging is by using a properties file, and invoking Java with:
-Djava.util.logging.config.file=path/to/file/logging.properties
The reason is that the settings you do sometimes are not applied to loggers created before you loaded the settings, once some changes have been made to the logging.

Log4j: Multiple categories with specializations

I have some doubts about the categories of log4j.
I have three categories ...
Program
Program.BUILD
Program.QUERY
When I define the following log4j.properties:
log4j.logger.program = DEBUG, stdout, file
log4j.logger.program.BUILD = DEBUG, file
and in Java I call:
Logger logger = Logger.getLogger("program.BUILD");
assume that the stdout and file are the appender to console and file respectively.
My problem is that when I specify the two categories, as shown, `program.BUILD log's are written to console and file. But he was only specified for the file appender. The log4j then makes it an inheritance?
I would like to specify three categories, but that when specified he caught the program.BUILD ONLY what was specified in that category, without taking the generic category (program).
But if not specified, the categories program.QUERY and program.BUILD, was picking up the program category, because it would represent the two that were not specified.
How can I do this?
Yes, Log4j has an inheritance system. You can disable it (that is, not let the log messages bubble up to the parent category) with the "additivity=false" flag.
Each enabled logging request for a given logger will be forwarded to
all the appenders in that logger as well as the appenders higher in
the hierarchy. In other words, appenders are inherited additively from
the logger hierarchy. For example, if a console appender is added to
the root logger, then all enabled logging requests will at least print
on the console. If in addition a file appender is added to a logger,
say C, then enabled logging requests for C and C's children will print
on a file and on the console. It is possible to override this default
behavior so that appender accumulation is no longer additive by
setting the additivity flag to false.
(See http://logging.apache.org/log4j/1.2/manual.html)

java logging API, disable logging to standard output

Using the standard java logging API (import java.util.logging.Logger), after the construction:
Logger l = Logger.getLogger("mylogger");
I am already able to log something. Since it has not a FileHandler, it doesn't write anything to disk.
l.severe("test with no handler");
It writes (some, not all) the log messages to output.
How can I disable this feature?
thanks in advance
Agostino
The question arises if you don't know the default configuration of java util logging.
Architectural fact:
0)Every logger whatever its name is has the root logger as parent.
Default facts:
1) the logger property useParentHandlers is true by default
2) the root logger has a ConsoleHandler by default
So. A new logger, by default sends its log records also to his parent(point 1) that is the root logger(point 0) wich, by default, logs them to console(point 2).
Remove console logging is easy as:
Logger l0 = Logger.getLogger("");
l0.removeHandler(l0.getHandlers()[0]);
Standard Loggers in Java are in a hierarchical structure and child Loggers by default inherit the Handlers of their parents. Try this to suppress parent Handlers from being used:
l.setUseParentHandlers(false);
By disable this feature you mean you don't want to log anything at all? If that's the case you have to set the level of that logger to NONE
For instance, if you're using a logging properties file you can set:
mylogger.level=NONE

Categories

Resources