Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.apache.marmotta.platform.core.services.logging;
 
 
 import java.io.File;
 import java.util.*;
LoggingServiceImpl

Author(s):
Sebastian Schaffert
 
 public class LoggingServiceImpl implements LoggingService {
     private static Logger log = LoggerFactory.getLogger(LoggingService.class);
 
     @Inject
 
 
     @Inject
 
 
 
     private ConsoleOutput consoleOutput;
 
     private LoggerContext loggerContext;
 
 
     @PostConstruct
     public void initialize() {
         .info("Apache Marmotta Logging Service starting up ...");
 
          = new HashMap<>();
 
          = CacheBuilder.newBuilder().maximumSize(10).expireAfterAccess(10, .).build(
                 new CacheLoader<StringLogFileOutput>() {
                    @Override
                    public LogFileOutput load(String keythrows Exception {
                        if(.isConfigurationSet("logging.file."+key+".name")) {
                            return new LogFileOutput(key);
                        } else {
                            throw new MarmottaConfigurationException("logfile configuration "+key+" not found");
                        }
                    }
                }
        );
         = CacheBuilder.newBuilder().maximumSize(5).expireAfterAccess(10, .).build(
                new CacheLoader<StringSyslogOutput>() {
                    @Override
                    public SyslogOutput load(String keythrows Exception {
                        if(.isConfigurationSet("logging.syslog."+key+".name")) {
                            return new SyslogOutput(key);
                        } else {
                            throw new MarmottaConfigurationException("syslog configuration "+key+" not found");
                        }
                    }
                }
        );
         = (LoggerContext) LoggerFactory.getILoggerFactory();
        .info("- configured logging modules: {}", StringUtils.join(Iterables.transform(listModules(), new Function<LoggingModuleObject>() {
            @Override
            public Object apply(LoggingModule input) {
                return input.getName();
            }
        }), ", "));
        .info("- configured logging appenders: {}", StringUtils.join(Iterables.transform(listOutputConfigurations(), new Function<LoggingOutputObject>() {
            @Override
            public Object apply(LoggingOutput input) {
                return input.getName();
            }
        }),", "));
    }
    public void startEventHandler(@Observes LoggingStartEvent event) {
        if(!.getBooleanConfiguration("testing.enabled")) {
            .warn("LOGGING: Switching to Apache Marmotta logging configuration; further output will be found in {}{}log{}*.log".getHome(), ..);
            configureLoggers();
        }
    }
        if(!.getBooleanConfiguration("testing.enabled")) {
            if (event.containsChangedKeyWithPrefix("logging.")) {
                .warn("LOGGING: Reloading logging configuration");
                configureLoggers();
            }
        }
    }


    
Configure all loggers according to their configuration and set some reasonable fallback for the root level (WARN to console, INFO to main logfile)
    private void configureLoggers() {
        // remove all existing appenders
        .reset();
        for(LoggingOutput output : listOutputConfigurations()) {
            configureOutput(output);
        }
        for(LoggingModule module : listModules()) {
            configureModule(module);
        }
        // configure defaults for root logger
        rootLogger.detachAndStopAllAppenders();
        rootLogger.addAppender(.get(getOutputConfiguration("console")));
        rootLogger.addAppender(.get(getOutputConfiguration("main")));
    }

    
Configure output appenders using the configuration given as argument.

Parameters:
output
    private void configureOutput(LoggingOutput output) {
        Appender<ILoggingEventappender = .get(output);
        // stop old existing appender
        if(appender != null) {
            appender.stop();
        }
        // create new appender based on configuration
        if(output instanceof ConsoleOutput) {
            appender = new ConsoleAppender<>();
            PatternLayoutEncoder pl = new PatternLayoutEncoder();
            pl.setContext();
            pl.setPattern(output.getPattern());
            pl.start();
            ((ConsoleAppender)appender).setEncoder(pl);
        } else if(output instanceof LogFileOutput) {
            String basePath = .getHome() + . + "log" + .;
            appender = new RollingFileAppender<>();
            ((RollingFileAppender)appender).setFile(basePath + ((LogFileOutputoutput).getFileName());
            TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
            policy.setContext();
            policy.setMaxHistory(((LogFileOutputoutput).getKeepDays());
            policy.setFileNamePattern(basePath + ((LogFileOutputoutput).getFileName() + ".%d{yyyy-MM-dd}.gz");
            policy.setParent((FileAppenderappender);
            policy.start();
            ((RollingFileAppenderappender).setRollingPolicy(policy);
            PatternLayoutEncoder pl = new PatternLayoutEncoder();
            pl.setContext();
            pl.setPattern(output.getPattern());
            pl.start();
            ((RollingFileAppenderappender).setEncoder(pl);
        } else if(output instanceof SyslogOutput) {
            appender = new SyslogAppender();
            ((SyslogAppender)appender).setSyslogHost(((SyslogOutputoutput).getHostName());
            ((SyslogAppender)appender).setFacility(((SyslogOutputoutput).getFacility());
            ((SyslogAppenderappender).setSuffixPattern(output.getPattern());
        } else {
            throw new IllegalArgumentException("unknown logging output type: "+output.getClass().getName());
        }
        appender.setContext();
        appender.setName(output.getId());
        ThresholdFilter filter = new ThresholdFilter();
        filter.setLevel(output.getMaxLevel().toString());
        filter.setContext();
        filter.start();
        appender.addFilter(filter);
        appender.start();
        .put(output,appender);
    }


    
Add the logging configuration for the given module. This method will create loggers for all packages covered by the module and add the appenders configured for the module

Parameters:
module
    private void configureModule(LoggingModule module) {
        for(String pkg : module.getPackages()) {
            ch.qos.logback.classic.Logger logger = .getLogger(pkg);
            logger.detachAndStopAllAppenders();
            logger.setAdditive(false);
            logger.setLevel(module.getCurrentLevel());
            for(LoggingOutput appender : module.getLoggingOutputs()) {
                logger.addAppender(.get(appender));
            }
        }
    }

    
    @Override
    @Produces
    public Logger createLogger(InjectionPoint injectionPoint) {
        return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass());
    }


    
Create a new logfile output configuration using the given parameters; further options can be set on the object itself.

Parameters:
id unique identifier for the log output configuration
name human-readable name for configuration (displayed in UI)
file filename under MARMOTTA_HOME/log
Returns:
    @Override
    public LogFileOutput createLogFileOutput(String idString nameString file) {
        try {
            return .get(id);
        } catch (ExecutionException e) {
            LogFileOutput r = new LogFileOutput(id);
            r.setFileName(file);
            r.setName(name);
            return r;
        }
    }

    
Return a list of all output configurations, reading directly from the configuration service.

Returns:
    @Override
        List<LoggingOutputlogs = new ArrayList<>();
        logs.addAll(
                Lists.transform(.listConfigurationKeys(Pattern.compile("logging\\.(file|syslog)\\.([^\\.]+)\\.name")), new Function<MatcherLoggingOutput>() {
                    @Override
                    public LoggingOutput apply(java.util.regex.Matcher input) {
                        return getOutputConfiguration(input.group(2));
                    }
                }
                ));
        logs.add();
        return logs;
    }

    
Return the output configuration with the given ID.

Parameters:
id
Returns:
    @Override
        if("console".equals(id)) {
            return ;
        }
        try {
            return .get(id);
        } catch (ExecutionException e) {
        }
        try {
            return .get(id);
        } catch (ExecutionException e) {
        }
        return null;
    }

    
Create a new syslog output configuration using the given parameters; further options can be set on the object itself. If not set, the default hostname is "localhost" and the default facility is "LOCAL0".

Parameters:
id unique identifier for the log output configuration
name human-readable name for configuration (displayed in UI)
Returns:
    @Override
    public SyslogOutput createSyslogOutput(String idString name) {
        try {
            return .get(id);
        } catch (ExecutionException e) {
            SyslogOutput r = new SyslogOutput(id,);
            r.setName(name);
            return r;
        }
    }

    
Return the console output configuration used by Marmotta. There is only a single console output for any Marmotta instance.

Returns:
    @Override
    public ConsoleOutput getConsoleOutput() {
        return ;
    }

    
Return a list of all modules found on the classpath. This list is assembled via CDI injection. Since modules are managed beans, calling setters on the LoggingModule implementations will directly change the configuration.

Returns:
    @Override
    public List<LoggingModulelistModules() {
        List<LoggingModuleresult = Lists.newArrayList();
        Collections.sort(resultnew Comparator<LoggingModule>() {
            @Override
            public int compare(LoggingModule o1LoggingModule o2) {
                return Collator.getInstance().compare(o1.getName(), o2.getName());
            }
        });
        return result;
    }
New to GrepCode? Check out our FAQ X