6

I am developing a framework and I want the jar to be light weight and independent as much as it can be.

So I wrote a logging class:

import java.util.Date;
import java.util.Properties;

public class Logger {

    private static final Logger me = new Logger();
    private static boolean info = false;
    private static boolean debug = false;
    private static boolean error = false;
    private static String className = null;

    public static Logger getInstance(Class<?> clazz) {  
        className = clazz.getCanonicalName();
        try {
            Properties props = new CustProps().load(clazz);
            if(props.get(CustProps.NAME_LOG_MODE) != null) {
                String devMode = props.getProperty(CustProps.NAME_LOG_MODE)
                                   .toLowerCase();
                if("info".equals(devMode)) {
                    info = true;
                    debug = true;
                } else if("debug".equals(devMode)) {
                    debug = true;
                } 
            }
        } catch (Exception e) {
            // debug is error by default
        }

        error = true;
        return me;
    }

    public void logError(Object msg) {
        if(isError()) {
            System.out.println(new Date().toString()
              + " ERROR ["+Logger.className+"] - " + msg);
        }
    }

    public void logDebug(Object msg) {
        if(isDebug()) {
            System.out.println(new Date().toString()
              + " DEBUG ["+Logger.className+"] - " + msg);
        }
    }

    public void logInfo(Object msg) {
        if(isInfo()) {
            System.out.println(new Date().toString()
              + " INFO ["+Logger.className+"] - " + msg);
        }
    }

    public boolean isInfo() { return Logger.info; }

    public boolean isDebug() { return Logger.debug; }

    public boolean isError() { return Logger.error; }

}
  • What are the best practices to make this logging better?
  • Is making your own logger even worth it?
  • Will the use of this logger make my framework worse than choosing something existing (like log4j)?
SovietFrontier
  • 2,047
  • 1
  • 15
  • 33
Trick
  • 3,779
  • 12
  • 49
  • 76

7 Answers7

25

I would STRONGLY recommend that you use slf4j as your logging API, as it is designed to be able to switch backends at deployment time. In other words, if you ever outgrow your own logging framework or has to interface with others using something else, it is simple to change your mind.

http://slf4j.org/

It also allows you to use the {}-construction for easy inserting objects in your log strings without overhead if that string is not actually logged anyway (which is really nice).

I'll suggest you consider adapting the "Simple" backend to your needs since it probably provides 90% of what you want.

http://www.slf4j.org/apidocs/org/slf4j/impl/SimpleLogger.html

Note: Do not use any backend directly (like log4j or java.util.logging) as it will essentially lock your code to that backend. Use a facade.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • 1
    Given that the logging frameworks such as java.util.log* or log4j are pretty extensible and configurable is it really worth going via a facade (admitedly a very good facade). Have you ever come across a need that is not met by log4j? – djna Nov 20 '09 at 14:19
  • slf4j provides the {}-construction. That alone warrants the use everywhere. – Thorbjørn Ravn Andersen Nov 20 '09 at 15:53
  • Thanks for the recommendation, but still - for java.util.logging.Logger I don't need extra imports. – Trick Nov 23 '09 at 08:51
  • Now 10 years later I think that the design behind slf4j (as the API for logback) is broken in that logging should not be an invisible bit of your application, but a first class component. For a new project I would recommend looking into log4j version 2 and use the native API. https://logging.apache.org/log4j/2.x/ – Thorbjørn Ravn Andersen Jan 31 '21 at 22:53
  • *Have you ever come across a need that is not met by log4j?* **Umm, a secure supply chain?** – Andrew Henle Mar 11 '22 at 16:41
13

Don't you like java.util.logging.Logger? It is included into JDK, you don't need anything else.

Dmitry
  • 3,740
  • 15
  • 17
7

You ask three questions:

  • What are best practices to make this logging better?

As others have noted, the best practice would be to replace it entirely, either with something like log4j or slf4j, or, to meet your "independence" goal, simply with java.util.Logger.

  • Is making your own logger even worth it?

No, except in very specialized circumstances, where for some reason, the existing frameworks don't meet your needs. You've said nothing to indicate that that might be the case.

  • Will the use of this logger make my framework worse than choosing something existing (like log4j)?

Yes, if for no other reason than that it will make other maintainers spend a few minutes reading your logging class when they come into your codebase. Using an existing framework means they already know what it does.

CPerkins
  • 8,968
  • 3
  • 34
  • 47
  • Sensible advice. I have lost count of the number of times I see people writing their own frameworks (often pretty good) but they lose interest by the time if comes to document them.. – Fortyrunner Nov 21 '09 at 07:32
  • Great Answer. But I got a follow up question. We have a product with 5 different micro-services. We are developing a common library for that to handle cross-cutting concerns. What common logging features could be handled in it? I thought of a couple like: 1- Logging Pattern, 2- Logging Library activities, 3- Common logging configuration. But trying to find more values into it. Thanks in advance. – Mustafa Mohammadi Apr 15 '19 at 13:29
  • 1
    @MustafaMohammadi pose that as a question on its own, and it'll get more traction. Also, you'll need to specify a bit more information on the problem. I still don't see _why_ you want to develop a common logging library. The wheel is pretty good as it is. – CPerkins Apr 17 '19 at 13:45
3

Use log4j. It is not a heavy weight logging framework, what do you mean by "independent as much as it can be"?
Just add the log4j jar to your framework and you are good to go.

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
3

Nothing's more lightweight than using java.util.logging.Logger, since it's already available in the JRE.

Kaleb Brasee
  • 51,193
  • 8
  • 108
  • 113
2

Why re-invent the wheel?

If you use the Java util logging library then it's already in the JDK and so you have no extra code to provide.

Otherwise, log4j is surely pretty good.

djna
  • 54,992
  • 14
  • 74
  • 117
0

I would agree with the other comments - use a COTS tool (either Logger, Log4j or other). Writing and maintaining your own is (usually) not worth it.

One more point to consider: If your framework contains other 3rd party software that you'd like integrated into one log file, you'd have to use some shared tool (e.g. the one supported by that 3rd party software). It is often very helpful to have all pieces of the system consolidate logs into one place.

Armadillo
  • 1,408
  • 11
  • 9