For complex applications it is useful to have a flexible logging framework. In which the logging can be sent to different destinations, for example a database, a file or the console in a format the can be configured at any time and that can filter out the desired messages depending on the environment. For example all messages in the development environment or only errors in the production environment. The Log4j framework offers all these functionalities. The previously mentioned features can be configured in a .properties file. In this way the logging can be configured without touching the source code.

Matlab ships with this log4j framework, but the framework is not part of the official Matlab Documentation. The Java archive can be found in \MATLAB\R2019b\java\jarext\log4j.jar
Note that this is the Apache Log4j version 1 and not the Apache Log4j version 2.

The code fragment below shows how to initialize a Logger.

% Import the Java code for the logger.

import org.apache.log4j.Logger;

% Read settings from the file.


% Create a logger by specifying its name, the logger can be retrieved by using this name.

logger = Logger.getLogger('loggername');

The created Logger can be retrieved by using its name. This is useful when the same logger is used in different functions or .m files.
The code fragment below shows how to retrieve a previously created Logger.

% Import the java code for the logger.

import org.apache.log4j.Logger;

% Retrieve the previously created logger by using its name

logger = Logger.getLogger('loggername');

One of the powers of the log4j framework is that log messages can be specified for different levels. In the code fragment below log messages are issued for different log levels.
The log handlers, which redirect the logging messages to for example a file, the console or a database, can be configured to only log messages fatal errors in the production environment and all log messages in the development environment.

logger.debug('debug message')'info message')

logger.warn('warn message')

logger.error('error message')

logger.fatal('fatal message')

The power of the log4j framework is that by using a log4j properties file the logging can be configurated.
Below two examples: more info can be found:
Below a code fragment of a log4j.poperties file for logging to a file ('logger.log').






log4j.appender.file.layout.conversionPattern=%d [%t] %-5p %c - %m%n



log4j.appender.file.DatePattern = '.'yyyyMMddHHmm



Below a code fragment of a log4j.poperties file for logging to the console..

log4j.rootCategory=debug, console







log4j.appender.console.layout.conversionPattern=%d [%t] %-5p %c - %m%n