Logger not functioning properly - java

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.

Related

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.

Java logging all except one

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

Logging in spring MVC

I'm currently working on a web application using Spring MVC, and I use the #ExceptionHandler annotation in every controllers of the application.
So basically I got a method like this:
#ExceptionHandler(RuntimeException.class)
public String handleException(RuntimeException ex) {
injectedService.notifyAndLogException(ex.getMessage());
return ("error_page");
}
My idea is to log and send an email to an application administrator in the injected service.
For now, I've tried to read some documentation about logging in spring application, and all the things I've seen is setting a static logger in each controller.
Like this:
private final Logger log = LoggerFactory.getLogger(Controller.class);
#ExceptionHandler(RuntimeException.class)
public String handleException(RuntimeException ex) {
log.info("Logging error");
injectedService.notifyException(ex.getMessage());
return ("error_page");
}
I'd like to know what is the point to use a logger in each controller instead of using it in one point only (the service)?
I'd like to know what is the point to use a logger in each controller instead of using it in one point only
If you use a single logger for the whole application, then every log message will be logged as coming from the same component. By using a logger per class or component, then your log files will contain information about which component logged the message.
For example, when you do:
Logger log = LoggerFactory.getLogger(Controller.class);
This creates a logger with the name of the Controller class, which will generally be displayed in the log file, e.g.
2012-03-07:12:59:00 com.x.y.Controller Hello!
This is just a convention, but it's a good one that I advise you follow.
a logger in each of your class files enables you get 'debug' or 'info' level when you are in production, or not able to connect a debugger.
Since you can limit via package or even class file name, what is logged, you can pin point to find errors, or to see what is happening under different load situations (concurrency problems, resources used ). If you use one generic logger, then you may flood your log file.
With the logger in the class that received the exception, you may be able to get at class variables that are not being passed into your exception handler.
I would also recommend that you do not do
injectedService.notifyAndLogException(ex.getMessage());
but pass the exception into your notify. While stack traces can be notorious verbose, the messages usually are not very help full ( NullPointerException without a stacktrace ? ). In your notify service you can set the subject to ex.getMessage() and the body have the entire stack trace.
Your controllers can extend an abstract class that declares a logger like that
protected Logger logger = LoggerFactory.getLogger( getClass() );
This logger can be used in all controller and it will prefix the log message with the controller class name.

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