HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Log4j Singleton

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
log4jsingletonstackoverflow

Problem

I'm trying to design and develop a singleton class that will handle resolution and configuration of log4j (not log4j2). The basic idea is to have a single class, reusable in any application, that handles log4j configuration and management.

I want the following features available:

  • Singleton, one instance, conserve memory



  • XML and DOMConfigurator



  • Ability to use a JVM Argument: -Dorg.jbjf.log4j=./etc/app-log4j.xml to configure the log4j during startup



  • Ability to return Logger objects using a getLog (String loggerName)



-
Configure the log4j framework based on an XML file that can be:

  • From a full/partial dir-path/filename.xml



  • From a CLASSPATH like URL /log4j.xml



  • Provide some basic getter/setter methods to manage different Logger objects as needed using Logger.name. Also, need a way to pass in a new XML file and re-configure the log4j framework.



```
package org.jbjf.core;

import java.io.File;
import java.net.URL;
import java.util.Enumeration;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.xml.DOMConfigurator;

/**
*
* The RootLogger is a simple log4j singleton class
* that provides an easy management interface to configure, get, set,
* re-configure the log4j framework for your application.
*
*
* Dependencies:
*
* JRE/JDK 6(+)
*
*
*
* Details
*
* Input Resources
*
*
*
* Method
*  
* Usage
*  
* Description/Comments
*
*
*
* getEndTime/setEndTime
*  
* Runtime
*  
*
* Provides a JBJF ...
*
*
*
*
*
* Example(s)
*
*
*
*
*
* @author Adym S. Lincoln
* Copyright (C) 2006-2017. JBJF, All rights reserved.
* @version 1.0.0
* @since 1.0.0
*
*
* @see org.jbjf
*
*/

public final class RootLogger {

/**
* Stores

Solution

You mix up the singelton object pattern as defined by the "Gang of Four" in the book "Design patterns" with the Java singelton pattern.

The Java singelton pattern is the attempt to force singulatity of an object of a certain class programmatically, but this usually brings more problems then it solves.

The first an (IMHO) most important problem is: it is hard to mock (but not impossible, I know...) and therefore it is hard to verify that my code correctly communicates with your code in a unit test.

Then: it is not expendable. What if I want to add my on JSon-based configuration, or read the config from a database?

So when you continue to write your alternative to slf4j try to make the lives of your users easier, not harder.

Context

StackExchange Code Review Q#153314, answer score: 2

Revisions (0)

No revisions yet.