How to remove package name from log line?

121 Views Asked by At

The Java util logging uses the following output line format:

java.util.logging.SimpleFormatter.format = %4$s %2$s %n

This gives the following output, where first main is a package name, while the last main is a method name:

INFO main.MySuperPuperClassName main

How to eliminate of the package name here? So that the resulting log line would look like this:

INFO MySuperPuperClassName main

The idea is to not output the package name in the log line.

2

There are 2 best solutions below

0
VGR On BEST ANSWER

I’m pretty sure you cannot do this with logging properties alone. However, you can write your own Formatter class:

import java.time.ZonedDateTime;
import java.time.ZoneId;

import java.io.StringWriter;
import java.io.PrintWriter;

import java.util.IllegalFormatException;

import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;

public class NoPackageFormatter
extends SimpleFormatter {
    private static final String FORMAT_PROPERTY =
        "java.util.logging.SimpleFormatter.format";

    private static final String DEFAULT_FORMAT = "%4$s %2$s%6$s%n";
    // Java SE's default for US English locale
    //private static final String DEFAULT_FORMAT =
    //    "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n";

    private static final ZoneId ZONE = ZoneId.systemDefault();

    private static String stripPackage(String name) {
        return name.substring(name.lastIndexOf('.') + 1);
    }

    @Override
    public String format(LogRecord record) {
        String formatString = System.getProperty(FORMAT_PROPERTY);
        if (formatString == null) {
            formatString =
                LogManager.getLogManager().getProperty(FORMAT_PROPERTY);
        }
        if (formatString == null) {
            formatString = DEFAULT_FORMAT;
        }

        String name = record.getLoggerName();
        name = stripPackage(name);

        String sourceClass = record.getSourceClassName();
        String sourceMethod = record.getSourceMethodName();
        String source = sourceClass != null && sourceMethod != null ?
            stripPackage(sourceClass) + ' ' + sourceMethod : name;

        String stackTrace = "";
        if (record.getThrown() != null) {
            StringWriter writer = new StringWriter();
            record.getThrown().printStackTrace(new PrintWriter(writer));
            stackTrace = System.lineSeparator() + writer;
        }

        Object[] args = {
            record.getInstant().atZone(ZONE),
            source,
            name,
            record.getLevel().getLocalizedName(),
            formatMessage(record),
            stackTrace
        };

        try {
            return String.format(formatString, args);
        } catch (IllegalFormatException e) {
            return String.format(DEFAULT_FORMAT, args);
        }
    }
}

To use it, you can refer to it in logging properties:

java.util.logging.ConsoleHandler.formatter: com.example.NoPackageFormatter
java.util.logging.FileHandler.formatter:    com.example.NoPackageFormatter
java.util.logging.SocketHandler.formatter:  com.example.NoPackageFormatter

Or, you can set it programmatically:

private static final Logger logger;

static {
    logger = Logger.getLogger(MyApplication.class.getName());

    Formatter formatter = new NoPackageFormatter();

    for (Logger l = logger; l != null; l = l.getParent()) {
        for (Handler handler : l.getHandlers()) {
            handler.setFormatter(formatter);
        }
    }
}
5
Sombriks On

EDIT

changing log declaration to

  private static final Logger LOG = Logger.getLogger(FooBar.class.getSimpleName());

and the logging configuration to

java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s: %3$s %5$s %n

gives the exact result expected.

See long answer for examples and context.


You can find all documentation needed to proper create a log string here: https://docs.oracle.com/javase/7/docs/api/java/util/logging/SimpleFormatter.html#format(java.util.logging.LogRecord)

Here you get good information about the logging.properties file: https://docs.geotools.org/latest/userguide/library/metadata/logging/java_logging.html

from what you're presenting as output, your log config might be being ignored and that's why you don't see results. did you set the property configuration before run the code? https://stackoverflow.com/a/54068185/420096

For example, this java file and this configuration in same folder:

import java.util.logging.Logger;

public class FooBar {

  private static final Logger LOG = Logger.getLogger("my");

  public static void main(String ...args) {
    LOG.info("I was there");
  }
}

The file logging.properties:

handlers= java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s: %3$s %2$s %5$s %n

You can test the logging with this command line:

java -Djava.util.logging.config.file=logging.properties FooBar.java

And expect an output like this:

2024-01-07 08:35:07 INFORMAÇÕES: my FooBar main I was there

Where "my" in the output is whatever you use as logger name. Class simple name, for example:

https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getSimpleName