Skip to content

Instantly share code, notes, and snippets.

@gkhays
Last active January 19, 2024 13:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkhays/091a78b1aa14b601668e to your computer and use it in GitHub Desktop.
Save gkhays/091a78b1aa14b601668e to your computer and use it in GitHub Desktop.
Logging with Log4j and Apache Commons

Apache Commons and Log4J Logging

This article illustrates a quick start to using Log4J and commons logging. Obtaining a log factory and logging to various levels is fairly straight-forward. What can be tricky is getting the properties files correct. The code snippet below depends on:

  • commons-logging-1.1.jar
  • log4j-1.2.16.jar
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Log4jExample {

	static Log log = LogFactory.getLog(Log4jExample.class);

	public static void main(String[] args) {
		log.debug("Hello this is a debug message");
		log.error("Hello an error occurred");
		log.info("Hello this is an info message");
	}
}

Under Eclipse, the log property files should be managed as resources. Accordingly, save them to the root of src or use src/main/resources for J2EE projects.

The commons-logging properties file. In this case, we indicate that we wish to use the Log4j logger (and consequently a log4j properties file). Commons logging looks for the commons-logging.properties file in the classpath.

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
log4j.configuration=log4j.properties

Log4J properties file.

# Define the root logger with appender file
#log = /usr/local/logs
#log4j.rootLogger = DEBUG, FILE, stdout
log4j.rootLogger=warn,FILE,stdout

# Define the file appender
#log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.FILE.File=${log}/log.out
#log4j.appender.FILE.File=${log}/log4j.log
log4j.appender.FILE.File=log4j.log

# Rolling attributes
log4j.appender.FILE.MaxFileSize=100KB
log4j.appender.FILE.MaxBackupIndex=2

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.FILE.layout.conversionPattern=%m%n
log4j.appender.FILE.layout.ConversionPattern=%d{ISO8601} %5p %t %c{4}:%L - %m%n

# Include a console appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p %t %c{4}:%L - %m%n

# Log4jExample settings
log4j.logger.org.gkh.Log4jExample=debug

Since many projects use an XML properties file, I've included one here. As a side note, I attempted to use <pre> and <code> tags to show XML syntax highlighting but ended up with a blank panel, so I instead use the triple backtick format. See How to post raw XML in github comment.

<Configuration status="WARN">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

Console and log file output. Following is the output based upon our Java source and configuration files. See full log output.

2016-03-17 19:30:39,371 DEBUG main com.netiq.Log4jExample:41 - Hello this is a debug message
2016-03-17 19:30:39,384 ERROR main com.netiq.Log4jExample:42 - Hello an error occurred
2016-03-17 19:30:39,384  INFO main com.netiq.Log4jExample:43 - Hello this is an info message

JVM switches in Eclipse; for troubleshooting -- I used these to determine which logger was being invoked.

-Dlog4j.debug=true
-Dorg.apache.commons.logging.diagnostics.dest=STDOUT

JVM Switches

See Troubleshooting logging configuration (Log4j, commons-logging) for more detail.

References

  1. Configuring Log4j 2
  2. Extras - Rolling Log File Appernder
  3. Daily Rolling File Appender
  4. Log4j Logging in Files
  5. Log4j XML Example
  6. Write log file using org.apache.commons.logging
  7. No appenders could be found for logger(log4j)?
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
log4j.configuration=log4j.properties
# Define the root logger with appender file
#log = /usr/local/logs
#log4j.rootLogger = DEBUG, FILE, stdout
log4j.rootLogger=warn,FILE,stdout
# Define the file appender
#log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.FILE.File=${log}/log.out
#log4j.appender.FILE.File=${log}/log4j.log
log4j.appender.FILE.File=log4j.log
# Rolling attributes
log4j.appender.FILE.MaxFileSize=100KB
log4j.appender.FILE.MaxBackupIndex=2
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.FILE.layout.conversionPattern=%m%n
log4j.appender.FILE.layout.ConversionPattern=%d{ISO8601} %5p %t %c{4}:%L - %m%n
# Include a console appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p %t %c{4}:%L - %m%n
# Log4jExample settings
log4j.logger.com.netiq.Log4jExample=debug
# ManageDsaItTest Logging
log4j.logger.com.netiq.ManageDsaItTest=debug
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="com.mojang">
<Appenders>
<Console name="SysOut" target="SYSTEM_OUT">
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n" />
</Console>
<Queue name="DevelopmentConsole">
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n" />
</Queue>
<Async name="Async">
<AppenderRef ref="SysOut"/>
<AppenderRef ref="DevelopmentConsole"/>
</Async>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Async"/>
</Root>
</Loggers>
</Configuration>
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Extension directories (java.ext.dir): null
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Application classpath (java.class.path): C:\Users\haysg\Development\WorkBench\Snippets\Snippets\bin;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jackson-core-2.4.4.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jaxen-1.1.6.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jackson-databind-2.4.4.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jettison-1.3.2.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\commons-logging-1.1.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\commons-logging-adapters-1.1.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\commons-logging-api-1.1.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\log4j-1.2.16.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\commons-logging-1.1.1.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jackson-core-2.1.3.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jsr305-1.3.9.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jersey-bundle-1.17.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\google-oauth-client-jetty-1.19.0.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\google-oauth-client-java6-1.19.0.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jetty-util-6.1.26.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jetty-6.1.26.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\servlet-api-2.5-20081211.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\google-oauth-client-1.19.0.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\google-http-client-1.19.0.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\google-api-client-1.19.0.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\google-http-client-jackson2-1.19.0.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\unboundid-ldapsdk-se.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\svnkit-1.8.10.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\ojdbc7.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\jdom-2.0.5.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\sqljet-1.1.10.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\svnkit-cli-1.8.10.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\sequence-library-1.0.3.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\svnkit-javahl16-1.8.10.jar;C:\Users\haysg\Development\WorkBench\Snippets\Snippets\lib\netiq-ags.jar
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Class org.apache.commons.logging.LogFactory was loaded via classloader sun.misc.Launcher$AppClassLoader@521681009
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Ancestry of classloader which loaded org.apache.commons.logging.LogFactory is sun.misc.Launcher$AppClassLoader@521681009 == 'sun.misc.Launcher$AppClassLoader@1f183871'
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Ancestry of classloader which loaded org.apache.commons.logging.LogFactory is ClassLoader tree:sun.misc.Launcher$AppClassLoader@521681009 (SYSTEM) --> sun.misc.Launcher$ExtClassLoader@1864471209 --> BOOT
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] BOOTSTRAP COMPLETED
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] LogFactory implementation requested for the first time for context classloader sun.misc.Launcher$AppClassLoader@521681009
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] sun.misc.Launcher$AppClassLoader@521681009 == 'sun.misc.Launcher$AppClassLoader@1f183871'
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] ClassLoader tree:sun.misc.Launcher$AppClassLoader@521681009 (SYSTEM) --> sun.misc.Launcher$ExtClassLoader@1864471209 --> BOOT
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] Properties file found at 'file:/C:/Users/haysg/Development/WorkBench/Snippets/Snippets/bin/commons-logging.properties' with priority 0.0
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] Properties file of name 'commons-logging.properties' found at 'file:/C:/Users/haysg/Development/WorkBench/Snippets/Snippets/bin/commons-logging.properties"
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] Looking for system property [org.apache.commons.logging.LogFactory] to define the LogFactory subclass to use...
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] No system property [org.apache.commons.logging.LogFactory] defined.
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] Looking for a resource file of name [META-INF/services/org.apache.commons.logging.LogFactory] to define the LogFactory subclass to use...
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] No resource file with name 'META-INF/services/org.apache.commons.logging.LogFactory' found.
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] Looking in properties file for entry with key 'org.apache.commons.logging.LogFactory' to define the LogFactory subclass to use...
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] Properties file has no entry specifying LogFactory subclass.
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] [LOOKUP] Loading the default LogFactory implementation 'org.apache.commons.logging.impl.LogFactoryImpl' via the same classloader that loaded this LogFactory class (ie not looking in the context classloader).
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] Loaded class org.apache.commons.logging.impl.LogFactoryImpl from classloader sun.misc.Launcher$AppClassLoader@521681009
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Instance created.
[LogFactory from sun.misc.Launcher$AppClassLoader@521681009] Created object org.apache.commons.logging.impl.LogFactoryImpl@1947164567 to manage classloader sun.misc.Launcher$AppClassLoader@521681009
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Discovering a Log implementation...
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Trying to get configuration for item org.apache.commons.logging.Log.allowFlawedContext
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No LogFactory attribute found for org.apache.commons.logging.Log.allowFlawedContext
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No system property found for property org.apache.commons.logging.Log.allowFlawedContext
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No configuration defined for item org.apache.commons.logging.Log.allowFlawedContext
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Trying to get configuration for item org.apache.commons.logging.Log.allowFlawedDiscovery
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No LogFactory attribute found for org.apache.commons.logging.Log.allowFlawedDiscovery
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No system property found for property org.apache.commons.logging.Log.allowFlawedDiscovery
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No configuration defined for item org.apache.commons.logging.Log.allowFlawedDiscovery
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] Trying to get configuration for item org.apache.commons.logging.Log.allowFlawedHierarchy
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No LogFactory attribute found for org.apache.commons.logging.Log.allowFlawedHierarchy
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No system property found for property org.apache.commons.logging.Log.allowFlawedHierarchy
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [ENV] No configuration defined for item org.apache.commons.logging.Log.allowFlawedHierarchy
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Trying to get log class from attribute 'org.apache.commons.logging.Log'
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Attempting to load user-specified log class 'org.apache.commons.logging.impl.Log4JLogger'...
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Attempting to instantiate 'org.apache.commons.logging.impl.Log4JLogger'
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Trying to load 'org.apache.commons.logging.impl.Log4JLogger' from classloader sun.misc.Launcher$AppClassLoader@521681009
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Class 'org.apache.commons.logging.impl.Log4JLogger' was found at 'jar:file:/C:/Users/haysg/Development/WorkBench/Snippets/Snippets/lib/commons-logging-1.1.jar!/org/apache/commons/logging/impl/Log4JLogger.class'
log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@1f183871.
log4j: Trying to find [log4j.xml] using sun.misc.Launcher$AppClassLoader@1f183871 class loader.
log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource().
log4j: Trying to find [log4j.properties] using context classloader sun.misc.Launcher$AppClassLoader@1f183871.
log4j: Using URL [file:/C:/Users/haysg/Development/WorkBench/Snippets/Snippets/bin/log4j.properties] for automatic log4j configuration.
log4j: Reading configuration from URL file:/C:/Users/haysg/Development/WorkBench/Snippets/Snippets/bin/log4j.properties
log4j: Parsing for [root] with value=[warn,FILE,stdout].
log4j: Level token is [warn].
log4j: Category root set to WARN
log4j: Parsing appender named "FILE".
log4j: Parsing layout options for "FILE".
log4j: Setting property [conversionPattern] to [%d{ISO8601} %5p %t %c{4}:%L - %m%n].
log4j: End of parsing for "FILE".
log4j: Setting property [maxBackupIndex] to [2].
log4j: Setting property [maxFileSize] to [100KB].
log4j: Setting property [file] to [log4j.log].
log4j: setFile called: log4j.log, true
log4j: setFile ended
log4j: Parsed "FILE" options.
log4j: Parsing appender named "stdout".
log4j: Parsing layout options for "stdout".
log4j: Setting property [conversionPattern] to [%d{ISO8601} %5p %t %c{4}:%L - %m%n].
log4j: End of parsing for "stdout".
log4j: Setting property [target] to [System.out].
log4j: Parsed "stdout" options.
log4j: Parsing for [com.netiq.Log4jExample] with value=[debug].
log4j: Level token is [debug].
log4j: Category com.netiq.Log4jExample set to DEBUG
log4j: Handling log4j.additivity.com.netiq.Log4jExample=[null]
log4j: Parsing for [com.netiq.ManageDsaItTest] with value=[debug].
log4j: Level token is [debug].
log4j: Category com.netiq.ManageDsaItTest set to DEBUG
log4j: Handling log4j.additivity.com.netiq.ManageDsaItTest=[null]
log4j: Finished configuring.
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] [INFO] 'org.apache.commons.logging.impl.Log4JLogger' from classloader sun.misc.Launcher$AppClassLoader@521681009 does not declare optional method setLogFactory(LogFactory)
[LogFactoryImpl@1947164567 from sun.misc.Launcher$AppClassLoader@521681009] Log adapter 'org.apache.commons.logging.impl.Log4JLogger' from classloader sun.misc.Launcher$AppClassLoader@521681009 has been selected for use.
2016-03-17 19:30:39,371 DEBUG main com.netiq.Log4jExample:41 - Hello this is a debug message
2016-03-17 19:30:39,384 ERROR main com.netiq.Log4jExample:42 - Hello an error occurred
2016-03-17 19:30:39,384 INFO main com.netiq.Log4jExample:43 - Hello this is an info message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment