Loggers implementation in java
A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.swing. In addition it is possible to create «anonymous» Loggers that are not stored in the Logger namespace. Logger objects may be obtained by calls on one of the getLogger factory methods. These will either create a new Logger or return a suitable existing Logger. It is important to note that the Logger returned by one of the getLogger factory methods may be garbage collected at any time if a strong reference to the Logger is not kept. Logging messages will be forwarded to registered Handler objects, which can forward the messages to a variety of destinations, including consoles, files, OS logs, etc. Each Logger keeps track of a «parent» Logger, which is its nearest existing ancestor in the Logger namespace. Each Logger has a «Level» associated with it. This reflects a minimum Level that this logger cares about. If a Logger’s level is set to null, then its effective level is inherited from its parent, which may in turn obtain it recursively from its parent, and so on up the tree. The log level can be configured based on the properties from the logging configuration file, as described in the description of the LogManager class. However it may also be dynamically changed by calls on the Logger.setLevel method. If a logger’s level is changed the change may also affect child loggers, since any child logger that has null as its level will inherit its effective level from its parent. On each logging call the Logger initially performs a cheap check of the request level (e.g., SEVERE or FINE) against the effective log level of the logger. If the request level is lower than the log level, the logging call returns immediately. After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent’s Handlers, recursively up the tree. Each Logger may have a ResourceBundle associated with it. The ResourceBundle may be specified by name, using the getLogger(java.lang.String, java.lang.String) factory method, or by value — using the setResourceBundle method. This bundle will be used for localizing logging messages. If a Logger does not have its own ResourceBundle or resource bundle name, then it will inherit the ResourceBundle or resource bundle name from its parent, recursively up the tree. Most of the logger output methods take a «msg» argument. This msg argument may be either a raw value or a localization key. During formatting, if the logger has (or inherits) a localization ResourceBundle and if the ResourceBundle has a mapping for the msg string, then the msg string is replaced by the localized value. Otherwise the original msg string is used. Typically, formatters use java.text.MessageFormat style formatting to format parameters, so for example a format string » » would format two parameters as strings. A set of methods alternatively take a «msgSupplier» instead of a «msg» argument. These methods take a Supplier function which is invoked to construct the desired log message only when the message actually is to be logged based on the effective log level thus eliminating unnecessary message construction. For example, if the developer wants to log system health status for diagnosis, with the String-accepting version, the code would look like:
class DiagnosisMessages < static String systemHealthStatus() < // collect system health information . >> . logger.log(Level.FINER, DiagnosisMessages.systemHealthStatus());
With the above code, the health status is collected unnecessarily even when the log level FINER is disabled. With the Supplier-accepting version as below, the status will only be collected when the log level FINER is enabled.
logger.log(Level.FINER, DiagnosisMessages::systemHealthStatus);
- There are a set of «log» methods that take a log level, a message string, and optionally some parameters to the message string.
- There are a set of «logp» methods (for «log precise») that are like the «log» methods, but also take an explicit source class name and method name.
- There are a set of «logrb» method (for «log with resource bundle») that are like the «logp» method, but also take an explicit resource bundle object for use in localizing the log message.
- There are convenience methods for tracing method entries (the «entering» methods), method returns (the «exiting» methods) and throwing exceptions (the «throwing» methods).
- Finally, there are a set of convenience methods for use in the very simplest cases, when a developer simply wants to log a simple string at a given log level. These methods are named after the standard Level names («severe», «warning», «info», etc.) and take a single argument, a message string.
Field Summary
Initialization of this field is prone to deadlocks. The field must be initialized by the Logger class initialization which may cause deadlocks with the LogManager class initialization. In such cases two class initialization wait for each other to complete. The preferred way to get the global logger object is via the call Logger.getGlobal() . For compatibility with old JDK versions where the Logger.getGlobal() is not available use the call Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) or Logger.getLogger(«global») .
Constructor Summary
Method Summary
Log a CONFIG message, which is only to be constructed if the logging level is such that the message will actually be logged.
Log a FINE message, which is only to be constructed if the logging level is such that the message will actually be logged.
Log a FINER message, which is only to be constructed if the logging level is such that the message will actually be logged.
Log a FINEST message, which is only to be constructed if the logging level is such that the message will actually be logged.
Log a INFO message, which is only to be constructed if the logging level is such that the message will actually be logged.
Log a message, which is only to be constructed if the logging level is such that the message will actually be logged.
Log a message, specifying source class and method, with a single object parameter to the log message.
Log a lazily constructed message, specifying source class and method, with associated Throwable information.
Log a message, specifying source class, method, and resource bundle, with an optional list of message parameters.
Log a message, specifying source class, method, and resource bundle, with associated Throwable information.
Logger in Java — Java Logging Example
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Logger in Java
Java Logging API was introduced in 1.4 and you can use java logging API to log application messages. In this java logging tutorial, we will learn basic features of Java Logger. We will also look into Java Logger example of different logging levels, Logging Handlers, Formatters, Filters, Log Manager and logging configurations.
Java Logger
java.util.logging.Logger is the class used to log application messages in java logging API. We can create java Logger with very simple one line code as;
Logger logger = Logger.getLogger(MyClass.class.getName());
Java Logging Levels
- SEVERE (highest)
- WARNING
- INFO
- CONFIG
- FINE
- FINER
- FINEST
There are two other logging levels, OFF that will turn off all logging and ALL that will log all the messages. We can set the logger level using following code:
The logs will be generated for all the levels equal to or greater than the logger level. For example if logger level is set to INFO, logs will be generated for INFO, WARNING and SEVERE logging messages.
Java Logging Handlers
We can add multiple handlers to a java logger and whenever we log any message, every handler will process it accordingly. There are two default handlers provided by Java Logging API.
- ConsoleHandler: This handler writes all the logging messages to console
- FileHandler: This handler writes all the logging messages to file in the XML format.
We can create our own custom handlers also to perform specific tasks. To create our own Handler class, we need to extend java.util.logging.Handler class or any of it’s subclasses like StreamHandler, SocketHandler etc. Here is an example of a custom java logging handler:
package com.journaldev.log; import java.util.logging.LogRecord; import java.util.logging.StreamHandler; public class MyHandler extends StreamHandler < @Override public void publish(LogRecord record) < //add own logic to publish super.publish(record); >@Override public void flush() < super.flush(); >@Override public void close() throws SecurityException < super.close(); >>
Java Logging Formatters
Formatters are used to format the log messages. There are two available formatters in java logging API.
- SimpleFormatter: This formatter generates text messages with basic information. ConsoleHandler uses this formatter class to print log messages to console.
- XMLFormatter: This formatter generates XML message for the log, FileHandler uses XMLFormatter as a default formatter.
We can create our own custom Formatter class by extending java.util.logging.Formatter class and attach it to any of the handlers. Here is an example of a simple custom formatter class.
package com.journaldev.log; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; public class MyFormatter extends Formatter < @Override public String format(LogRecord record) < return record.getThreadID()+"::"+record.getSourceClassName()+"::" +record.getSourceMethodName()+"::" +new Date(record.getMillis())+"::" +record.getMessage()+"\n"; >>
Logger in Java — Java Log Manager
java.util.logging.LogManager is the class that reads the logging configuration, create and maintains the logger instances. We can use this class to set our own application specific configuration.
LogManager.getLogManager().readConfiguration(new FileInputStream("mylogging.properties"));
Here is an example of Java Logging API Configuration file. If we don’t specify any configuration, it’s read from JRE Home lib/logging.properties file. mylogging.properties
handlers= java.util.logging.ConsoleHandler .level= FINE # default file output is in user's home directory. java.util.logging.FileHandler.pattern = %h/java%u.log java.util.logging.FileHandler.limit = 50000 java.util.logging.FileHandler.count = 1 java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter # Limit the message that are printed on the console to INFO and above. java.util.logging.ConsoleHandler.level = INFO java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter com.journaldev.files = SEVERE
Here is a simple java program showing usage of Logger in Java.
package com.journaldev.log; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; public class LoggingExample < static Logger logger = Logger.getLogger(LoggingExample.class.getName()); public static void main(String[] args) < try < LogManager.getLogManager().readConfiguration(new FileInputStream("mylogging.properties")); >catch (SecurityException | IOException e1) < e1.printStackTrace(); >logger.setLevel(Level.FINE); logger.addHandler(new ConsoleHandler()); //adding custom handler logger.addHandler(new MyHandler()); try < //FileHandler file name with max size and number of log files limit Handler fileHandler = new FileHandler("/Users/pankaj/tmp/logger.log", 2000, 5); fileHandler.setFormatter(new MyFormatter()); //setting custom filter for FileHandler fileHandler.setFilter(new MyFilter()); logger.addHandler(fileHandler); for(int i=0; ilogger.log(Level.CONFIG, "Config data"); > catch (SecurityException | IOException e) < e.printStackTrace(); >> >
When you will run above java logger example program, you will notice that CONFIG log is not getting printed in file, that is because of MyFilter class.
package com.journaldev.log; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; public class MyFilter implements Filter < @Override public boolean isLoggable(LogRecord log) < //don't log CONFIG logs in file if(log.getLevel() == Level.CONFIG) return false; return true; >>
Also the output format will be same as defined by MyFormatter class.
1::com.journaldev.log.LoggingExample::main::Sat Dec 15 01:42:43 PST 2012::Msg977 1::com.journaldev.log.LoggingExample::main::Sat Dec 15 01:42:43 PST 2012::Msg978 1::com.journaldev.log.LoggingExample::main::Sat Dec 15 01:42:43 PST 2012::Msg979 1::com.journaldev.log.LoggingExample::main::Sat Dec 15 01:42:43 PST 2012::Msg980
If we don’t add our own Formatter class to FileHandler, the log message will be printed like this.
2012-12-14T17:03:13 1355533393319 996 com.journaldev.log.LoggingExample INFO com.journaldev.log.LoggingExample main 1 Msg996
Console log messages will be of following format:
Dec 15, 2012 1:42:43 AM com.journaldev.log.LoggingExample main INFO: Msg997 Dec 15, 2012 1:42:43 AM com.journaldev.log.LoggingExample main INFO: Msg998 Dec 15, 2012 1:42:43 AM com.journaldev.log.LoggingExample main INFO: Msg998
Below image shows the final Java Logger example project. That’s all for Logger in Java and Java Logger Example. You can download the project from below link.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.