logo
down
shadow

How to configure java.util.logging via properties to use standard output?


How to configure java.util.logging via properties to use standard output?

Content Index :

How to configure java.util.logging via properties to use standard output?
Tag : java , By : Techspirit
Date : January 12 2021, 07:00 PM

this will help Derive a new handler from java.util.logging.StreamHandler and use its fully-qualified name with a .handlers property.
(If Apache Maven is used, be aware of the surefire plugin using stdout as a means of IPC with its forked children, so expect corruption warnings during testing, see here.)
mkdir -p /tmp/logger/{src/org.foo/{{classes,tests}/org/foo/logging{,/internal},resources},{build/modules/org.foo,dist}}
cd /tmp/logger && gio tree --hidden
file:///tmp/logger
|-- build
|   `-- modules
|       `-- org.foo
|-- dist
`-- src
    `-- org.foo
        |-- classes
        |   `-- org
        |       `-- foo
        |           `-- logging
        |               `-- internal
        |-- resources
        `-- tests
            `-- org
                `-- foo
                    `-- logging
                        `-- internal
package org.foo.logging.internal;

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.util.Objects;

import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;

public class StandardOutConsoleHandler extends StreamHandler
{
    public StandardOutConsoleHandler(Formatter formatter)
    {
        super(new FileOutputStream(FileDescriptor.out),
                Objects.requireNonNull(formatter, "formatter"));
    }

    public StandardOutConsoleHandler() { this(new SimpleFormatter()); }

    /* Taken from java.logging/java.util.logging.ConsoleHandler. */
    @Override
    public void publish(LogRecord record)
    {
        super.publish(record);
        flush();
    }

    /* Taken from java.logging/java.util.logging.ConsoleHandler. */
    @Override
    public void close() { flush(); }
}
package org.foo.logging.internal;

import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
import java.util.Objects;

import java.util.logging.Filter;
import java.util.logging.LogRecord;

public class WallClockTimeFilter implements Filter
{
    private static final TemporalQuery<Boolean> BUSINESS_HOURS
                                            = new BusinessHours();

    static class BusinessHours implements TemporalQuery<Boolean>
    {
        private static final LocalTime FROM = LocalTime.of(9, 0);
        private static final LocalTime TO = LocalTime.of(17, 0);

        @Override
        public Boolean queryFrom(TemporalAccessor temporal)
        {
            final LocalTime now = LocalTime.from(temporal);
            return (now.isAfter(FROM) && now.isBefore(TO));
        }
    }

    @Override
    public boolean isLoggable(LogRecord record)
    {
        Objects.requireNonNull(record, "record");
        final LocalTime now = LocalTime.ofInstant(record.getInstant(),
                                                ZoneId.systemDefault());
        return now.query(BUSINESS_HOURS);
    }
}
package org.foo.logging.internal;

import java.io.IOException;
import java.io.InputStream;

import java.util.logging.LogManager;

/*
 * This class could be referenced on the command-line as follows
 *
 * -Djava.util.logging.config.class=org.foo.logging.internal.LoggingPropertiesConfigurer
 *
 * See java.logging/java.util.logging.LogManager#readConfiguration().
 */
public class LoggingPropertiesConfigurer
{
    private static final String RESOURCE = "/logging.properties";

    public LoggingPropertiesConfigurer() throws IOException
    {
        try (final InputStream is = getClass().getResourceAsStream(
                                                        RESOURCE)) {
            if (is == null)
                throw new IllegalStateException(
                        String.format("Unavailable resource: '%s'",
                                                        RESOURCE));

            /* Prefer new non-null values over old values. */
            LogManager.getLogManager().updateConfiguration(is,
                                                    property ->
                                ((oldValue, newValue) -> {
                return (oldValue == null && newValue == null)
                    ? null  /* Discard the property. */
                    : (newValue == null)
                        ? oldValue
                        : newValue;
            }));
        }
    }
}
package org.foo.logging;

import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

import java.util.logging.Logger;

import org.foo.logging.internal.LoggingPropertiesConfigurer;

public class Dummy
{
    static {
        try {
            final String fileName = System.getProperty(
                            "java.util.logging.config.file");
            final String klassName = System.getProperty(
                            "java.util.logging.config.class");

            if (klassName == null && fileName == null)
                new LoggingPropertiesConfigurer();
        } catch (final IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    static Optional<Logger> getLogger()
    {
        /*
         * Note that for any org.foo.Bar.Baz.Quux member class
         * Class::getName returns an org.foo.Bar$Baz$Quux string,
         * therefore name accordingly these loggers, if any, in
         * the properties files, e.g.
         *      org.foo.Bar$Baz$Quux.level = WARNING
         */
        return Optional.ofNullable(Logger.getLogger(
                                        Dummy.class.getName()));
    }

    public static void main(String[] args)
    {
        /*
         * A weakly-reachable logger.
         *
         * See java.base/java.lang.ref.Reference#reachabilityFence(Object)
         */
        Dummy.getLogger().ifPresent(logger -> logger.warning(() ->
                                        Arrays.toString(args)));
    }
}
module org.foo {
    requires transitive java.logging;

    exports org.foo.logging;

    exports org.foo.logging.internal to
        java.logging;
}
javac -Xlint -d build/modules --module-source-path src/\*/classes/ $(find src/*/classes/ -type f -name \*.java)
java --describe-module org.foo --module-path build/modules
## From [java.home]/conf/logging.properties:
# handlers = java.util.logging.ConsoleHandler

handlers = org.foo.logging.internal.StandardOutConsoleHandler

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

## See the Javadoc of java.logging/java.util.logging.StreamHandler.
org.foo.logging.internal.StandardOutConsoleHandler.level = ALL
# org.foo.logging.internal.StandardOutConsoleHandler.filter = org.foo.logging.internal.WallClockTimeFilter
org.foo.logging.internal.StandardOutConsoleHandler.formatter = java.util.logging.SimpleFormatter
org.foo.logging.internal.StandardOutConsoleHandler.encoding = ISO-8859-1
cp -t build/modules/org.foo src/org.foo/resources/logging.properties
jar --create --module-version 0.0.1 --file dist/logger-0.0.1.jar --main-class org.foo.logging.Dummy -C build/modules/org.foo/ .
java -Xdiag --module-path dist/logger-0.0.1.jar --module org.foo raison d\'ĂȘtre 2>/dev/null
java -enablesystemassertions -Xdiag -Djava.util.logging.config.file=/path/to/jdk/conf/logging.properties --module-path dist/logger-0.0.1.jar --module org.foo raison d\'ĂȘtre 2>/dev/null

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to prevent java.util.logging.Logger to display messages on standard output?


Tag : java , By : Stephen Dewar
Date : March 29 2020, 07:55 AM
help you fix your problem If you're new to logging you should read Java Logging Overview. You should also post your configuration
This snippet shows how to write log messages into a file:
public static void main(String[] args){
    Handler fh = new FileHandler("%t/wombat.log");
    Logger.getLogger("").addHandler(fh);
    Logger.getLogger("com.wombat").setLevel("com.wombat",Level.FINEST);
    ...
}

How to configure java.util.logging.logger in android to use a logging properties file placed on the sdcard?


Tag : android , By : Mike
Date : March 29 2020, 07:55 AM
it should still fix some issue After going through the available documentation and doing some hit and trials. This is how it works:-
        static final String LOGGER_NAME = "com.robin.mylogger"
        LogManager lManager = LogManager.getLogManager();
        FileInputStream is = new FileInputStream(logProperties);
        if(lManager!=null) {
            lManager.readConfiguration(is);

        }
        mLoggerInstance = Logger.getLogger(LOGGER_NAME);
         if(mLoggerInstance!=null)
             LogManager.getLogManager().addLogger(mLoggerInstance);
               ############################################################
               #    Default Logging Configuration File
#
# You can use a different file by specifying a filename
# with the java.util.logging.config.file system property.  
# For example java -Djava.util.logging.config.file=myfile
############################################################

############################################################
#   Global properties
############################################################

# "handlers" specifies a comma separated list of log Handler 
# classes.  These handlers will be installed during VM startup.
# Note that these classes must be on the system classpath.
# By default we only configure a ConsoleHandler, which will only
# show messages at the INFO and above levels.
#handlers= java.util.logging.ConsoleHandler

# To also add the FileHandler, use the following line instead.
handlers= java.util.logging.FileHandler, com.android.internal.logging.AndroidHandler

# Default global logging level.
# This specifies which kinds of events are logged across
# all loggers.  For any given facility this global level
# can be overriden by a facility specific level
# Note that the ConsoleHandler also has a separate level
# setting to limit messages printed to the console.
.level= FINEST

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

# default file output is in user's home directory.
java.util.logging.FileHandler.pattern = /mnt/sdcard/csr/logs/test.log
java.util.logging.FileHandler.limit = 5000000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.level = FINEST
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter

# Limit the message that are printed on the console to INFO and above.
#java.util.logging.ConsoleHandler.level = FINEST
#java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

com.android.internal.logging.AndroidHandler.level = FINEST
com.android.internal.logging.AndroidHandler.formatter = java.util.logging.SimpleFormatter


############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#com.robin.mylogger.level = FINEST

How do i control mongo java driver logging using java.util.logging properties


Tag : mongodb , By : ravibits
Date : March 29 2020, 07:55 AM
wish helps you From: http://mongodb.github.io/mongo-java-driver/3.2/driver/reference/management/logging/
"By default, logging is enabled via the popular SLF4J API. The use of SLF4J is optional; the driver will use SLF4J if the driver detects the presence of SLF4J in the classpath. Otherwise, the driver will fall back to JUL (java.util.logging)"

java util logging configure filter in properties file


Tag : java , By : browe
Date : March 29 2020, 07:55 AM
like below fixes the issue The problem was the missing access modifier.
When the class was not specified with an access modifier it defaults to private-package which is only visible within the package. Therefore, the FileHandler reads the .filter property as null. When it is changed as public the filter was taken. The corrected code can be found below.
public class CustomFilter implements Filter {

 public boolean isLoggable(LogRecord record) {
    return record.getLoggerName().indexOf("com.package.name") != -1;
 }
}

Where should I put logging.properties file for java.util.logging in web application (maven project)?


Tag : java , By : CrimsonGore
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • how to use onBindViewHolder with multiple items in android RecyclerView
  • No ParameterResolver registered for parameter in BeforeAll method
  • Finding the path in a graph with the least casualties according to the lanchester square law
  • MongoWriteException when inserting into Mongodb with composite custom _id
  • Fetch Oracle procedure metadata with Java when multiple procedure signatures
  • Value modification of key-pair in HashMap and impact for a HashCode
  • Migration from solrj to spring-data-solr
  • How to check if you're still connected to the database with jpa
  • Use Date type in the graphql scheme
  • Split and add the string based on length
  • Is "main" method of spring boot application required when deploy as war
  • Getting the average within specific numbers in an array
  • how to use izpack to make my jar application to installer?
  • What is meant by src in Java Eclipse?
  • Create a mirrored linked list in Java
  • Examples of good JPA Java Desktop Application
  • Translate Java to Python -- signing strings with PEM certificate files
  • Algorithm Analysis tool for java
  • Java serial comm API - what does inputstream.read() return if a timeout occurs?
  • How do I make a background thread in Java that allows the main application to exit completely? This works in Linux, but
  • How to add an image dynamically at runtime in java
  • Java App on Mac asking for allow network connections everytime
  • Best actively maintained Java XMPP Library?
  • Multi-Threaded Application - Help with some pseudo code!
  • Scoping a StringBuilder inside a for loop
  • How to specify hash algorithm when updating LDAP via Java?
  • Class not found exception (org.apache.openjpa.enhance.PersistenceCapable) thrown in a client of WLS 10
  • In Java ,where in memory are class functions put?
  • How do I test expectedExceptionsMessageRegExp (exception message) using TestNG?
  • Help In understanding Multi Dimentional Arrays
  • No bean named '...' is defined and Spring @Resource annotation
  • Singleton design pattern vs Singleton beans in Spring container
  • flashvars object was not working in mozilla browser
  • Shell script to import mysql dump file
  • What are the best practices to separate data from users
  • May I use com.google.code prefix for my packages?
  • How to set classpath in manifest file , while creating JAR from eclipse?
  • dealing with voice in java
  • Error: java.security.AccessControlException: Access denied
  • How to verify the root trust of a ceritifcate
  • Searching for a standalone JSP compiler
  • Spring 2.5 managed servlets: howto?
  • iBatis get executed sql
  • GRAPH: find an algorithm to determine the shortest path from one point to another in a rectangular maze?
  • Efficient JSON encoding for data that may be binary, but is often text
  • How to Read Java File Structure using Java?
  • Java-Hibernate-Newbie: How do I acces the values from this list?
  • Smallest executable for Windows
  • Java: matching two different type of array
  • how to accept valid e-mail id in text box?
  • How can I know where a Null Pointer Exception originated?
  • Memory limited image processing in server
  • Java Multiple ResourceBundles
  • How to serialize Java primitives using Jersey REST
  • Casting objects to Integer,string ,
  • Using Java how can I plot the path of a sprite in a straight line?
  • IntelliJ shortcut for inserting a null check?
  • Eclipselink and update trigger on multiple access to the database
  • How to ICMPs and traceroutes in Java
  • "NOT_SUPPORTED_BY_GUI" Exception in JCo
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com