Search in sources :

Example 36 with LogManager

use of java.util.logging.LogManager in project janrufmonitor by tbrandt77.

the class LoggingInitializer method run.

public static void run() {
    File dir = new File(PathResolver.getInstance().getLogDirectory());
    if (!dir.exists())
        dir.mkdirs();
    LogManager lm = LogManager.getLogManager();
    // create PIM logger
    Logger log = Logger.getLogger(IJAMConst.DEFAULT_LOGGER);
    lm.addLogger(log);
    // set configuration
    try {
        File f = new File(PathResolver.getInstance().getConfigDirectory() + "logging.properties");
        InputStream in = new FileInputStream(f);
        String config = new String(LoggingInitializer.toByteArray(in));
        config = StringUtils.replaceString(config, IJAMConst.PATHKEY_LOGPATH, PathResolver.getInstance().getLogDirectory());
        config = StringUtils.replaceString(config, IJAMConst.PATHKEY_INSTALLPATH, PathResolver.getInstance().getInstallDirectory());
        config = StringUtils.replaceString(config, "\\", "/");
        ByteArrayInputStream is = new ByteArrayInputStream(config.getBytes());
        lm.readConfiguration(is);
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Logger(java.util.logging.Logger) File(java.io.File) LogManager(java.util.logging.LogManager) FileInputStream(java.io.FileInputStream)

Example 37 with LogManager

use of java.util.logging.LogManager in project narayana by jbosstm.

the class LraCheckerMavenPlugin method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    // do not show weld info log messages
    if (!getLog().isDebugEnabled()) {
        LogManager lm = LogManager.getLogManager();
        Logger archiveDeployerLogger = Logger.getLogger("org.jboss.weld");
        archiveDeployerLogger.setLevel(Level.WARNING);
        lm.addLogger(archiveDeployerLogger);
    }
    if (paths == null)
        paths = new String[] { project.getBuild().getOutputDirectory() };
    // check argument validity
    if (paths.length <= 0) {
        throw new MojoFailureException("No argument provided, nothing to be scanned");
    }
    String[] preprocessedPaths = paths;
    // filtering out paths that does not exist
    if (!failWhenPathNotExist) {
        preprocessedPaths = Arrays.asList(paths).stream().filter(path -> new File(path).exists()).toArray(String[]::new);
        if (preprocessedPaths.length <= 0) {
            getLog().warn("No provided parameter as path for checking for LRA classes '" + Arrays.asList(paths) + "' does exist");
            return;
        }
    }
    CheckerUtil.setMavenLog(getLog());
    getLog().info("Loading classes from paths: " + Arrays.asList(preprocessedPaths));
    // say if path is directory or jar file
    Map<File, FileType> pathsFileMap = classifyPaths(preprocessedPaths);
    // class loading from defined urls
    ClassLoader classLoader = providePathsToClassLoader(preprocessedPaths);
    // scanning the arguments to say the classes to be processed
    List<Class<?>> clazzNames = new ArrayList<Class<?>>();
    for (Entry<File, FileType> argEntry : pathsFileMap.entrySet()) {
        switch(argEntry.getValue()) {
            case DIRECTORY:
                clazzNames.addAll(CheckerUtil.loadFromDir(argEntry.getKey(), classLoader));
                break;
            case JAR:
                clazzNames.addAll(CheckerUtil.loadFromJar(argEntry.getKey(), classLoader));
                break;
        }
    }
    // weld extension checking the LRA annotation to go
    @SuppressWarnings("unchecked") Weld weld = new Weld().disableDiscovery().addExtensions(LraAnnotationProcessingExtension.class).setClassLoader(classLoader).addBeanClasses(clazzNames.toArray(new Class[clazzNames.size()]));
    try (WeldContainer container = weld.initialize()) {
    // weld intializes and works with extensions here
    } catch (org.jboss.weld.exceptions.DeploymentException ignore) {
        if (!getLog().isDebugEnabled()) {
            getLog().debug("Error on Weld init happened but we are ignoring" + "it as we care about LRA annotation and not about deploying", ignore);
        }
    } finally {
        if (!FailureCatalog.INSTANCE.isEmpty()) {
            throw new MojoFailureException(String.format("LRA annotation errors:%n%s", FailureCatalog.INSTANCE.formatCatalogContent()));
        }
    }
}
Also used : WeldContainer(org.jboss.weld.environment.se.WeldContainer) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ArrayList(java.util.ArrayList) Logger(java.util.logging.Logger) Weld(org.jboss.weld.environment.se.Weld) URLClassLoader(java.net.URLClassLoader) LogManager(java.util.logging.LogManager) File(java.io.File)

Example 38 with LogManager

use of java.util.logging.LogManager in project openj9 by eclipse.

the class LogCommand method displayLoggers.

private void displayLoggers() {
    LogManager lm = LogManager.getLogManager();
    TreeSet<String> names = new TreeSet<String>();
    for (Enumeration<String> e = lm.getLoggerNames(); e.hasMoreElements(); ) {
        Logger logger = lm.getLogger(e.nextElement());
        StringBuilder output = new StringBuilder();
        if (logger.getName().length() == 0) {
            output.append("<<default logger>>");
        } else {
            output.append(logger.getName());
        }
        if (logger.getHandlers().length == 0) {
            output.append(" : disabled");
        } else {
            output.append(" : enabled");
            output.append(" (");
            Level level = logger.getLevel();
            if (level != null) {
                String name = level.getName();
                output.append(name);
            }
            output.append(") ");
        }
        names.add(output.toString());
    }
    out.println("Currently installed loggers :-");
    for (String name : names) {
        out.print("\t");
        out.println(name);
    }
}
Also used : TreeSet(java.util.TreeSet) Level(java.util.logging.Level) Logger(java.util.logging.Logger) LogManager(java.util.logging.LogManager)

Example 39 with LogManager

use of java.util.logging.LogManager in project openj9 by eclipse.

the class LogCommand method configureLogger.

private void configureLogger(String name, String level) {
    LogManager lm = LogManager.getLogManager();
    Logger logger = lm.getLogger(name);
    if (name == null) {
        out.println("The logger name " + name + " was not recognised");
        return;
    }
    Level lvl = null;
    try {
        lvl = Level.parse(level);
    } catch (IllegalArgumentException e) {
        out.println("The level " + level + " was not recognised");
        return;
    }
    if (logger.getHandlers().length != 0) {
        // need to check for an existing console handler
        for (Handler handler : logger.getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                logger.setLevel(lvl);
                handler.setLevel(lvl);
                // reconfigure the existing handler
                return;
            }
        }
    }
    // if get this far then need to install a new console handler as one was not previously detected
    ConsoleHandler handler = new ConsoleHandler();
    logger.setLevel(lvl);
    handler.setLevel(lvl);
    logger.addHandler(handler);
}
Also used : ConsoleHandler(java.util.logging.ConsoleHandler) Handler(java.util.logging.Handler) Level(java.util.logging.Level) Logger(java.util.logging.Logger) LogManager(java.util.logging.LogManager) ConsoleHandler(java.util.logging.ConsoleHandler)

Example 40 with LogManager

use of java.util.logging.LogManager in project Payara by payara.

the class LogManagerService method postConstruct.

/**
 * Initialize the loggers
 */
@Override
public void postConstruct() {
    // if the system property is already set, we don't need to do anything
    if (System.getProperty("java.util.logging.config.file") != null) {
        System.out.println("\n\n\n#!## LogManagerService.postConstruct : java.util.logging.config.file=" + System.getProperty("java.util.logging.config.file"));
        return;
    }
    // logging.properties massaging.
    final LogManager logMgr = LogManager.getLogManager();
    File loggingPropertiesFile = null;
    // reset settings
    try {
        loggingPropertiesFile = getLoggingFile();
        System.setProperty("java.util.logging.config.file", loggingPropertiesFile.getAbsolutePath());
        String rootFolder = env.getProps().get(com.sun.enterprise.util.SystemPropertyConstants.INSTALL_ROOT_PROPERTY);
        String templateDir = rootFolder + File.separator + "lib" + File.separator + "templates";
        File src = new File(templateDir, ServerEnvironmentImpl.kLoggingPropertiesFileName);
        File dest = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName);
        System.out.println("\n\n\n#!## LogManagerService.postConstruct : rootFolder=" + rootFolder);
        System.out.println("#!## LogManagerService.postConstruct : templateDir=" + templateDir);
        System.out.println("#!## LogManagerService.postConstruct : src=" + src);
        System.out.println("#!## LogManagerService.postConstruct : dest=" + dest);
        if (!loggingPropertiesFile.exists()) {
            LOGGER.log(Level.FINE, "{0} not found, creating new file from template.", loggingPropertiesFile.getAbsolutePath());
            FileUtils.copy(src, dest);
            loggingPropertiesFile = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName);
        }
        logMgr.readConfiguration();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, LogFacade.ERROR_READING_CONF_FILE, e);
    }
    FormatterDelegate agentDelegate = null;
    if (agent != null) {
        agentDelegate = new AgentFormatterDelegate(agent);
    }
    // force the ConsoleHandler to use GF formatter
    String formatterClassName = null;
    try {
        Map<String, String> props = getLoggingProperties();
        formatterClassName = props.get(CONSOLEHANDLER_FORMATTER_PROPERTY);
        setConsoleHandlerLogFormat(formatterClassName, props, logMgr);
        // setting default attributes value for all properties
        setDefaultLoggingProperties(props);
        Collection<Handler> handlers = getHandlerServices(props);
        if (handlers != null && handlers.size() > 0) {
            // add the new handlers to the root logger
            for (Handler handler : handlers) {
                addHandler(handler);
            }
        }
        // add the filter if there is one
        String filterClassName = props.get(LoggingXMLNames.xmltoPropsMap.get("log-filter"));
        if (filterClassName != null) {
            Filter filterClass = habitat.getService(Filter.class, filterClassName);
            Logger rootLogger = Logger.getLogger("");
            if (rootLogger != null) {
                rootLogger.setFilter(filterClass);
            }
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, LogFacade.ERROR_APPLYING_CONF, e);
    }
    // Logger.getLogger() is still synchronized.
    synchronized (java.util.logging.Logger.class) {
        synchronized (logMgr) {
            Enumeration<String> loggerNames = logMgr.getLoggerNames();
            while (loggerNames.hasMoreElements()) {
                String loggerName = loggerNames.nextElement();
                Logger logger = logMgr.getLogger(loggerName);
                if (logger == null) {
                    continue;
                }
                for (Handler handler : logger.getHandlers()) {
                    Formatter formatter = handler.getFormatter();
                    if (formatter != null && formatter instanceof UniformLogFormatter) {
                        ((UniformLogFormatter) formatter).setDelegate(agentDelegate);
                    }
                }
            }
        }
    }
    // finally listen to changes to the loggingPropertiesFile.properties file
    listenToChangesOnloggingPropsFile(loggingPropertiesFile, logMgr);
    // Log the messages that were generated very early before this Service
    // started.  Just use our own logger...
    List<EarlyLogger.LevelAndMessage> catchUp = EarlyLogger.getEarlyMessages();
    if (!catchUp.isEmpty()) {
        for (EarlyLogger.LevelAndMessage levelAndMessage : catchUp) {
            LOGGER.log(levelAndMessage.getLevel(), levelAndMessage.getMessage());
        }
        catchUp.clear();
    }
    ArrayBlockingQueue<LogRecord> catchEarlyMessage = EarlyLogHandler.earlyMessages;
    while (!catchEarlyMessage.isEmpty()) {
        LogRecord logRecord = catchEarlyMessage.poll();
        if (logRecord != null) {
            LOGGER.log(logRecord);
        }
    }
}
Also used : Formatter(java.util.logging.Formatter) JSONLogFormatter(fish.payara.enterprise.server.logging.JSONLogFormatter) EarlyLogHandler(com.sun.enterprise.module.bootstrap.EarlyLogHandler) Handler(java.util.logging.Handler) PayaraNotificationFileHandler(fish.payara.enterprise.server.logging.PayaraNotificationFileHandler) ConsoleHandler(java.util.logging.ConsoleHandler) IOException(java.io.IOException) Logger(java.util.logging.Logger) EarlyLogger(com.sun.enterprise.util.EarlyLogger) EarlyLogger(com.sun.enterprise.util.EarlyLogger) AgentFormatterDelegate(com.sun.enterprise.v3.logging.AgentFormatterDelegate) IOException(java.io.IOException) ValidationException(javax.validation.ValidationException) AgentFormatterDelegate(com.sun.enterprise.v3.logging.AgentFormatterDelegate) Filter(java.util.logging.Filter) LogRecord(java.util.logging.LogRecord) GFLogRecord(com.sun.common.util.logging.GFLogRecord) LogManager(java.util.logging.LogManager) File(java.io.File)

Aggregations

LogManager (java.util.logging.LogManager)45 Logger (java.util.logging.Logger)19 Handler (java.util.logging.Handler)9 IOException (java.io.IOException)7 ClassLoaderLogManager (org.apache.juli.ClassLoaderLogManager)7 File (java.io.File)6 FileInputStream (java.io.FileInputStream)6 InputStream (java.io.InputStream)6 LifecycleException (org.apache.catalina.LifecycleException)6 ConsoleHandler (java.util.logging.ConsoleHandler)4 Level (java.util.logging.Level)4 FileNotFoundException (java.io.FileNotFoundException)3 LifecycleState (org.apache.catalina.LifecycleState)3 Server (org.apache.catalina.Server)3 AgentFormatterDelegate (com.sun.enterprise.v3.logging.AgentFormatterDelegate)2 PropertyChangeListener (java.beans.PropertyChangeListener)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Properties (java.util.Properties)2 Formatter (java.util.logging.Formatter)2 AfterClass (org.junit.AfterClass)2