Reconfigure log4j 1.x without restart

Disclaimer: This blog post is about log4j 1.x. which is by now a dormant project and not recommended for new projects. Logback and log4j 2.x support dynamic configuration changes at runtime via a simple attribute in their respective config files (see related log4j 2.x and logback docs). Please consider upgrading your logging backend to one of those libraries and use them in combination with the slf4j logging facade API.

Support for dynamic logging config changes at runtime is useful when you want to debug an application without restarting it: You can change settings in your logging config file, like log levels, appenders, log output formats, etc. and the logging framework automatically notices the change and reconfigures itself after a certain delay.

Good old log4j 1.x supports this, but you have to programatically set it up, typically somewhere in the start-up code of your Java application, using

  • DOMConfigurator.configureAndWatch(..) if you use log4j.xml
  • PropertyConfigurator.configureAndWatch(..) if you use log4j.properties

Please note that the log4j 1.x FAQ does not recommend doing this in a JEE container:

“Because the configureAndWatch launches a separate watchdog thread, and because there is no way to stop this thread in log4j 1.2, the configureAndWatch method is unsafe for use in J2EE environments where applications are recycled.”

The following example code works both for log4j.xml or log4j.properties files, as long as they are in the classpath as file resources, i.e. not packaged inside a jar:

    public static enum ConfigFileType {
         xml, properties
    }

    public void configureLogging(ConfigFileType configFileType) {
        final URL configFile = getClass().getResource("/log4j." + configFileType);

        if (configFile != null && "file".equals(configFile.getProtocol())) {
            final int scanDelayMinutes = getSystemProperty("log4j.config.rescan.delay.minutes", 2);
            final long scanDelayMillis = scanDelayMinutes * 60 * 1000;

            switch (configFileType) {
                case xml:
                    DOMConfigurator.configureAndWatch(configFile.getPath(), scanDelayMillis);
                    break;
                case properties:
                    PropertyConfigurator.configureAndWatch(configFile.getPath(), scanDelayMillis);
                    break;
            }
        }
    }

    private static int getSystemProperty(String name, int defaultValue) {
        try {
            return Integer.parseInt(System.getProperty(name));
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

You can override the default rescan delay as a system property option in your java command, for example:

java -Dlog4j.config.rescan.delay.minutes=5 [..]

The period is in minutes to prevent too much rescanning. Log4j uses a “FileWatchdog” class that repeatedly checks File#lastModified(). On some filesystems – like ReiserFS on Linux – scan delays of less than a minute can cause problems (thanks to Rod Oliveira for pointing this out).

AsciiDoc – A friendly authoring format

I recently learned about AsciiDoc, a powerful yet intuitive, human readable and writable format for authoring books and similar kinds of structured documents:

  • Solid technology, first created in 2002
  • Plain-text format, requires no special editor
  • Cleanly separates document structure from layout details
  • Available for the JVM community since 2013
  • Simple and intuitive like Markdown
  • As powerful as DocBook, without the XML clutter
  • Syntax highlighting in vim and other editors
  • Generates DocBook, HTML, epub, PDF, …
  • AsciiDoctor toolkit generates HTML 5, DocBook 4.5
  • Renders inline on github (like markdown)
  • Maven and Gradle plugins for automation
  • Support for creating diagrams using plain-text
  • Happily used by teams at Redhat, Git, Spring, …

For example, the whole documentation for the JEE standard CDI is maintained in AsciiDoc and hosted on github as maven buildable projects.

Dan Allen, a known name in the JEE community and AsciiDoctor lead developer, says that AsciiDoc supports “the creation of reusable, human-readable, semantic content” so that we can better adapt to adaptive content and address the challenges of an electronic multi-device, multi-format world that is redefining what “book” means.

An authoring revolution?

As an author-friendly plain-text format AsciiDoc might become a catalyst in an ongoing electronic authoring revolution that treats book writing like software development with authors working directly on the book’s “source code” in git repositories, while rendering into various target formats is done using build automation tools and fast scriptable converters like AsciiDoctor.

The tech-savvy publishing house O’Reilly seems to be on the forefront of this trend and

Use xtrlock via XFCE 4.8 lock button

I currently use XFCE 4.8 on Debian Wheezy as my desktop system. Its panel supports so-called “action buttons” for hibernate, lock, shutdown, etc.

I use one of those buttons to lock the screen but I don’t like xscreensaver (too ugly, don’t need the screensaver stuff), gnome-screensaver (too many dependencies), xlock and its successor xlockmore (too ugly) or slock (just a black blank screen always confuses me).

Good thing is that I found xtrlock which does what I want: It just shows a lock symbol instead of the mouse cursor, all screen content is still visible but user interaction is blocked until the current user password has been typed in.

This is just enough to prevent my 2 and 5 year old children from messing around with my laptop. So I installed it:

sudo apt-get install xtrlock

Problem was that the XFCE lock button calls xflock4 which is a simple shell script that has hardcoded support for the afore-mentioned set of lock programs, but not for xtrlock.

My simple solution was to take advantage of /usr/local/bin being usually before /usr/bin in the PATH and create a script /usr/local/bin/xflock4 with this content:

#!/bin/sh
xtrlock

Make it executable with

sudo chmod a+x /usr/local/bin/xflock4

Now I can use the XFCE lock button and get what I want.

Alternatively, there are a couple of other light-weight lock programs for Linux:

Halifax PD summit will feature a presentation about this blog

On April 30th, I will give a presentation “Blogging in the Open about professional experience” at the 2014 Halifax PD summit.

I will show how I use this public web log to share structured knowledge with an international community and serve as online documentation of gained expertise at the same time.

The presentation will cover features like one-click Publicize (to LinkedIn, Twitter, Google+, etc.), site stats, categorization and tagging, publishing embedded source code, search engine optimization and easy cross- browser testing.

The session should be useful for anyone who wants to combine structured knowledge sharing with social and professional networking.

Java software engineering – reference resources

Official Java and JEE

Java Technology Reference

Java Standard Edition (JSE)

Java Enterprise Edition (JEE)

The official Java tutorials

The official JEE 7 tutorial

JEE 7 Technologies index

Java language spec and JVM spec

Java community

Oracle Java community

OpenJDK

Java Community Process (JCP)

Apache Commons

Apache.org Java projects

JBoss.org

Spring

Google Guava

Trending Java projects on github

JEE and Java web servers

Apache Tomcat

JBoss Wildfly

Glassfish

Build and test automation

Sonatype Maven books

Jenkins documentation (wiki)

JUnit reference documentation

Source and version control

The SVN reference book

Git reference documentation

Java IDEs

Intellij IDEA documentation

Eclipse documentation

Netbeans knowledge base

Vim configuration for Java coding

Java remote debugging JVM options

Java 5, 6, 7 and newer

The Java™ Platform Debugger Architecture (JPDA) supports certain JVM invocation options.

Usually this boils down to:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=y

This will cause your JVM process to execute but wait (suspend=y) and listen for a socket connection from a remote debugging client on a free port (which it will write to stdout. The suspend=y option is especially useful if you need to debug code that runs during the start-up phase of your application.

If you don’t want the process to do the initial waiting, then use suspend=n.

Java 1.4

If you are for some terrible reason stuck on Java 1.4, then you must use the older approach like this:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n

Tomcat

To enabled remote debugging for a Apache Tomcat on Windows, create bin\setenv.bat in your Tomcat installation, with this content:

set "CATALINA_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n"

Network port

If you use the settings above, i.e. server=y and no “address” option, JPDA will pick a free port and write a message about this to stdout. Look for something like this:

Listening for transport dt_socket at address: [PORT]

Intellij configuration

Add a debug configuration via Run menu:

“Why do I have to pay for Redhat if it is ‘Free Software’?”

Unfortunately but quite naturally, there are many many people who are surprised when they first learn that “Free Software” is not necessarily available as a free-of-charge download in immediately usable (i.e. compiled binary) form.

“Free” is an ambiguous word in the English language: Free like “free beer” (= gratis, free of charge) versus free like “Free Speech” (= libre, based on guaranteed freedoms, liberties).

This ambiguity is an old problem of the term “Free Software” – first coined by the “Free Software Foundation” (FSF) in the 1980s – and was actually one factor that motivated the foundation of the “Open Source Initiative” (OSI) and its official definition of “Open Source”.

Both definitions use the same criteria and are essentially different names for the same category of software. To acknowledge and peacefully combine both of these naming conventions some people also speak of “Free/Libre Open Source Software” (FLOSS).

The Redhat Linux distribution is Free/Libre Open Source Software. The source code is licensed under the GPL and similar Open Source licenses and can be downloaded from Redhat’s ftp server. The binaries are not available as gratis download, which is perfectly in line with FLOSS rules.

For almost every IT professional these days, it is very beneficial to understand what “Free/Libre Open Source Software” (FLOSS) is. It might seem like a complex and dry subject at first, especially when some business folks confuse things further by using the vague term “Intellectual Property” for everything from copyright, trademarks, patents to license agreements, etc.

My first ~/.vimrc

I recently progressed from “the little vim-avoider who would if he only could” level to someone who actually edits his ~/.vimrc sometimes. So now I don’t want to forget the little I have learned and post it here:

" pointless reminder how i fixed vim issues on cygwin 
" existence of ~/.vimrc already triggers nocompatible mode
set nocompatible

" highlight all search pattern matches
set hlsearch

" i use light or even white background, vim to use readable colors
set bg=light

" use syntax highlighting
syntax on