Skip to content
Search

Log4j

lastmod 2025-02-14created 2014-06-0618 edits

log4j is a Java-based logging utility. It is mainly used as a debugging tool.

Recent versions of log4j have 6 log levels, from highest to lowest. Levels can be set per target (per package in Java) in the configuration file, and only logs at or above that level are stored.

Component List

Logger

The subject of logging (the class that writes the log file)

  • Sits at the heart of Log4j and lets developers control at runtime whether logs are output. A logger has a log level, and whether a log is output is decided by the level of the log statement and the level of the logger.
  • Before writing an application, you must decide which logger to use.
  • ex)
static Logger logger = Logger.getLogger(SimpleLog.class);
  • For reference, Commons-Logging also has a wrapper class

Appender

Where logs are output

  • Means the location where logs are output; looking at the names of the classes ending in XXXAppender in the Log4J API documentation gives a fair idea of the output location. 1
  • The main Appenders are shown in the following table.

Appender

Description

ConsoleAppender

Outputs log messages to the console.

FileAppender

Outputs log messages to a file,

RollingFileAppender

When the log reaches a specified size, outputs to a file with a different name.

DailyRollingFileAppender

Outputs log messages to a file on a daily basis.

SMTPAppender

Sends log messages by email.

NTEventLogAppender

Writes to the Windows event log system.

Layout

The output format of an Appender.

  • Various pieces of information such as date, time, and class name can be selected as the content of the log. Detailed patterns can be found in the class information below. 2
  • The types of Layout are as follows.
    1. DateLayout
    2. HTMLLayout
    3. PatternLayout (Using PatternLayout is generally best suited for debugging)
    4. SimpleLayout
    5. XMLLayout
  • The main patterns are as follows.

Pattern

Description

%d

Outputs the time the log was recorded.

%p

Outputs the priority of the log.

%F

Outputs the file name of the program where logging occurred.

%M

Outputs the name of the method where logging occurred.

%L

Outputs the line number of the caller where logging occurred.

%m

Outputs the log message.

%

n outputs a newline character.

Log4j log levels (Level)

ALL > TRACE > DEBUG > INFO > WARN > ERROR > FATAL > OFF

  • OFF: The OFF has the highest possible rank and is intended to turn off logging. Logging off.
  • ALL: The ALL has the lowest possible rank and is intended to turn on all logging. All logging.
  • TRACE: The TRACE Level designates finer-grained informational events than the DEBUG. Fine-grained
  • DEBUG: The DEBUG Level designates fine-grained informational events that are most useful to debug an application. Debugging.
  • INFO: The INFO level designates informational messages that highlight the progress of the application at coarse-grained level. Highlighted information.
  • WARN: The WARN level designates potentially harmful situations. Warning.
  • ERROR: The ERROR level designates error events that might still allow the application to continue running. Error.
  • FATAL: The FATAL level designates very severe error events that will presumably lead the application to abort. Severe error.

android-logging-log4j: Logging with Log4J in Android

Logging with Log4J in Android | providing LogCat appender, configuration facade and slf4j support.

Features:

  • logging in Android using log4j
  • support for logging with slf4j in Android using log4j
  • a LogCatAppender for log4j, which logs to LogCat
  • a log4j configuration facade class for convenient Log4J configuration
  • no modified log4j.jar is needed

Maven support:

<dependency>
  <groupId>de.mindpipe.android</groupId>
  <artifactId>android-logging-log4j</artifactId>
  <version>1.0.3</version>
</dependency>

Quickstart example using log4j in Android

Log4J configuration.

import java.io.File;
import org.apache.log4j.Level;
import android.os.Environment;
import de.mindpipe.android.logging.log4j.LogConfigurator;
/**
 * Call {@link #configure()}} from your application's activity.
 */
public class ConfigureLog4J {
    public static void configure() {
        final LogConfigurator logConfigurator = new LogConfigurator();

        logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "myapp.log");
        logConfigurator.setRootLevel(Level.DEBUG);
        // Set log level of a specific logger
        logConfigurator.setLevel("org.apache", Level.ERROR);
        logConfigurator.configure();
    }
}

Above code configures the log4j system with some default settings e.g.

  • file appender and LogCat appender
  • rotating logs and corresponding backup files and file sizes
  • default log output pattern

NOTE: In order to log to a file on the external storage, the following permission needs to be placed in AndroidManifest.xml.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Using log4j directly

causes smaller application sizes than using it through an abstraction layer e.g. with slf4j. In case of not using slf4j, you can save potentially about 36Kb. Prerequisites: (Add the following libraries to the classpath)

  • android-logging-log4j.jar
  • log4j.jar (version 1.2.x)
import org.apache.log4j.Logger;

public class ExampleLog4J {
    private final Logger log = Logger.getLogger(ExampleLog4J.class);

    public void myMethod() {
        log.info("This message should be seen in log file and logcat");
    }
}

Sample Log4jHelper class

package com.my.ledpowermgr.lib.debug;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import com.my.ledpowermgr.lib.DirectoryHelper;

/**
 * Log4j library helper class.
 * 
 * @author user
 * @since 140606
 */
public class Log4jHelper {

    private Log4jHelper() {
        throw new UnsupportedOperationException();
    }

    // -------------------
    // Constant valuables.
    // -------------------

    // public static final int MAX_LOG_FILE_SIZE_BYTE = 10 * 1024 * 1024;

    public static final String DEFAULT_LOGGER_NAME = "com.my.ledpowermgr";
    public static final Level DEFAULT_LOG_LEVEL = Level.DEBUG;

    public static final String FAVORITE_LOG_PATTERN = "[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5p [%l] - %m%n";
    public static final String DEFAULT_LOG_PATTERN = "[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5p - %m%n";

    public static final String DEFAULT_LOG_FILE_PREFIX = "LPM";
    public static final String DEFAULT_LOG_FILE_SUFFIX = ".log";
    public static final String DEFAULT_LOG_FILE_NAME = DEFAULT_LOG_FILE_PREFIX
            + DEFAULT_LOG_FILE_SUFFIX;
    public static final String DEFAULT_LOG_FILE_TIMESTAMP = "yyMMdd-HHmmss.SSS";

    /** Select ConsoleAppender or FileAppender for default Logger. */
    public static final boolean ENABLE_CONSOLE_PRINT = true;

    public static final boolean isConsolePrint() {
        return ENABLE_CONSOLE_PRINT;
    }

    // ----------
    // valuables.
    // ----------

    /** Logger object. */
    private static final Logger _log = Logger.getLogger(DEFAULT_LOGGER_NAME);

    /** is initialize. */
    private static boolean _init = false;

    public static void init() {
        init(getLogFilePath());
    }

    /** Initialize Log4j object. */
    public static void init(String path) {
        if (_init == false) {
            Appender appender = null;
            try {
                if (isConsolePrint() == true) {
                    appender = new ConsoleAppender(new PatternLayout(DEFAULT_LOG_PATTERN),
                            ConsoleAppender.SYSTEM_OUT);
                } else {
                    // 1Day on 1LogFile.
                    appender = new DailyRollingFileAppender(new PatternLayout(DEFAULT_LOG_PATTERN),
                            path, DEFAULT_LOG_FILE_TIMESTAMP);
                }

                _log.setLevel(DEFAULT_LOG_LEVEL);
                _log.addAppender(appender);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("Already been initialized.");
        }
    }

    private static String getLogFilePath() {
        return DirectoryHelper.getProjectLogDirectoryPath() + File.separator
                + DEFAULT_LOG_FILE_NAME;
    }

    // --------
    // Logging.
    // --------

    public static void trac(String message) {
        _log.trace(message);
    }

    public static void trac(String message, Throwable t) {
        _log.trace(message, t);
    }

    public static void debug(String message) {
        _log.debug(message);
    }

    public static void debug(String message, Throwable t) {
        _log.debug(message, t);
    }

    public static void info(String message) {
        _log.info(message);
    }

    public static void info(String message, Throwable t) {
        _log.info(message, t);
    }

    public static void warn(String message) {
        _log.warn(message);
    }

    public static void warn(String message, Throwable t) {
        _log.warn(message, t);
    }

    public static void error(String message) {
        _log.error(message);
    }

    public static void error(String message, Throwable t) {
        _log.error(message, t);
    }

    public static void fatal(String message) {
        _log.fatal(message);
    }

    public static void fatal(String message, Throwable t) {
        _log.fatal(message, t);
    }
}

See also

Favorite site

References

author Zer0 sitemap