Java Code Examples for org.slf4j.LoggerFactory

The following are top voted examples for showing how to use org.slf4j.LoggerFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jena   File: BlockMgrLogger.java View source code Vote up 7 votes
public BlockMgrLogger(Logger log, String label, BlockMgr blockMgr, boolean logAllOperations )
{
    this.blockMgr = blockMgr ;
    if ( log == null )
        log = LoggerFactory.getLogger(BlockMgr.class) ;
    this.log = log ;
    this.logAllOperations = logAllOperations ;
    this.label = label ;
}
 
Example 2
Project: visuwall   File: ApplicationHelper.java View source code Vote up 7 votes
public static void changeLogLvl() {
    try {
        InputStream logConfStream = ApplicationHelper.class.getResourceAsStream("/visuwall-logback.xml");
        String logConfString = CharStreams.toString(new InputStreamReader(logConfStream));
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(lc);
            lc.reset();
            configurator.doConfigure(new ByteArrayInputStream(logConfString.getBytes()));
        } catch (JoranException je) {
            je.printStackTrace();
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
    } catch (IOException e) {
        LOG.error("Can not change application log level", e);
    }

    // don't change root lvl as is may put hibernate or jetty in debug
    //        Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    //        root.setLevel(loglvl);
}
 
Example 3
Project: BerryMotesApp   File: EmoteDownloader.java View source code Vote up 7 votes
private void initLogging() {
	// reset the default context (which may already have been initialized)
	// since we want to reconfigure it
	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	lc.reset();

	// Log to logcat
	BasicLogcatConfigurator.configureDefaultContext();

	// If logging is enabled in settings, also log to file
	SharedPreferences settings = PreferenceManager
			.getDefaultSharedPreferences(mContext);
	if (settings.getBoolean(Settings.KEY_LOG, false)) {
		PatternLayoutEncoder encoder = new PatternLayoutEncoder();
		encoder.setContext(lc);
		encoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
		encoder.start();

		FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
		fileAppender.setContext(lc);
		fileAppender
				.setFile(new File(mContext.getFilesDir(), LOG_FILE_NAME)
						.getAbsolutePath());
		fileAppender.setEncoder(encoder);
		fileAppender.start();

		ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
				.getLogger(Logger.ROOT_LOGGER_NAME);
		root.addAppender(fileAppender);
	}
}
 
Example 4
Project: jentrata-msh   File: EBMSMessageHistoryQuerySenderTest.java View source code Vote up 6 votes
/** Setup the fixture. */

	@Before
	public void setUp() throws Exception {
		
		this.initTest();
		logger = LoggerFactory.getLogger(this.getName());
		logger.info(this.getName() + " Start ");	
		this.monitor.start();
		Thread.sleep(5000);
	}
 
Example 5
Project: logback-flume   File: PropertiesUtil.java View source code Vote up 6 votes
/**
 * Return the system properties or an empty Properties object if an error occurs.
 * @return The system properties.
 */
public static Properties getSystemProperties() {
    try {
        return new Properties(System.getProperties());
    } catch (final SecurityException ex) {
        LoggerFactory.getLogger(PropertiesUtil.class).error("Unable to access system properties.");
        // Sandboxed - can't read System Properties
        return new Properties();
    }
}
 
Example 6
Project: jena   File: TestList.java View source code Vote up 6 votes
/** Test that an iterator delivers the expected values */
protected static void iteratorTest( final Iterator<?> i,
		final Object[] expected )
{
	final Logger logger = LoggerFactory.getLogger(TestList.class);
	final List<Object> expList = new ArrayList<>();
	for (final Object element : expected)
	{
		expList.add(element);
	}

	while (i.hasNext())
	{
		final Object next = i.next();

		// debugging
		if (!expList.contains(next))
		{
			logger.debug("TestList - Unexpected iterator result: " + next);
		}

		Assert.assertTrue("Value " + next
				+ " was not expected as a result from this iterator ",
				expList.contains(next));
		Assert.assertTrue("Value " + next
				+ " was not removed from the list ", expList.remove(next));
	}

	if (!(expList.size() == 0))
	{
		logger.debug("TestList - Expected iterator results not found");
		for (final Object object : expList)
		{
			logger.debug("TestList - missing: " + object);
		}
	}
	Assert.assertEquals(
			"There were expected elements from the iterator that were not found",
			0, expList.size());
}
 
Example 7
Project: appstatus   File: LogbackLoggersManager.java View source code Vote up 6 votes
public List<LoggerConfig> getLoggers() {
	List<LoggerConfig> loggers = new ArrayList<LoggerConfig>();
	ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
	if (loggerFactory instanceof LoggerContext) {
		LoggerContext context = (LoggerContext) loggerFactory;
		for (ch.qos.logback.classic.Logger l : context.getLoggerList()) {
			loggers.add(new LoggerConfig(l.getName(), l.getEffectiveLevel().toString()));
		}
	}
	return loggers;
}
 
Example 8
Project: devcoin-android   File: WalletApplication.java View source code Vote up 6 votes
private void initLogging()
{
	final File logDir = getDir("log", Constants.TEST ? Context.MODE_WORLD_READABLE : MODE_PRIVATE);
	final File logFile = new File(logDir, "wallet.log");

	final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

	final PatternLayoutEncoder filePattern = new PatternLayoutEncoder();
	filePattern.setContext(context);
	filePattern.setPattern("%d{HH:mm:ss.SSS} [%thread] %logger{0} - %msg%n");
	filePattern.start();

	final RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
	fileAppender.setContext(context);
	fileAppender.setFile(logFile.getAbsolutePath());

	final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
	rollingPolicy.setContext(context);
	rollingPolicy.setParent(fileAppender);
	rollingPolicy.setFileNamePattern(logDir.getAbsolutePath() + "/wallet.%d.log.gz");
	rollingPolicy.setMaxHistory(7);
	rollingPolicy.start();

	fileAppender.setEncoder(filePattern);
	fileAppender.setRollingPolicy(rollingPolicy);
	fileAppender.start();

	final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
	logcatTagPattern.setContext(context);
	logcatTagPattern.setPattern("%logger{0}");
	logcatTagPattern.start();

	final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
	logcatPattern.setContext(context);
	logcatPattern.setPattern("[%thread] %msg%n");
	logcatPattern.start();

	final LogcatAppender logcatAppender = new LogcatAppender();
	logcatAppender.setContext(context);
	logcatAppender.setTagEncoder(logcatTagPattern);
	logcatAppender.setEncoder(logcatPattern);
	logcatAppender.start();

	final ch.qos.logback.classic.Logger log = context.getLogger(Logger.ROOT_LOGGER_NAME);
	log.addAppender(fileAppender);
	log.addAppender(logcatAppender);
	log.setLevel(Level.INFO);
}
 
Example 9
Project: MadStore   File: MadStoreConfigurationServletListener.java View source code Vote up 6 votes
private void initLogger() {
    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(MADSTORE_LOGGER_CONFIGURATION);
    if (inputStream == null) {
        throw new MadStoreConfigurationException("Logging configuration file " + MADSTORE_LOGGER_CONFIGURATION + " cannot be found");
    } else {
        if (LoggerFactory.getILoggerFactory() instanceof LoggerContext) {
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            try {
                JoranConfigurator configurator = new JoranConfigurator();
                configurator.setContext(loggerContext);
                loggerContext.reset();
                configurator.doConfigure(inputStream);
            } catch (JoranException ex) {
                loggerContext.reset();
                LOG.error(ex.getMessage(), ex);
            }
            StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
        } else {
            throw new MadStoreConfigurationException("Wrong logger factory of type: " + LoggerFactory.getILoggerFactory().getClass());
        }
    }
}
 
Example 10
Project: csrf-jhipster   File: LogsResource.java View source code Vote up 6 votes
@RequestMapping(value = "/rest/logs",
        method = RequestMethod.GET,
        produces = "application/json")
@Timed
public List<LoggerDTO> getList() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    List<LoggerDTO> loggers = new ArrayList<LoggerDTO>();
    for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
        loggers.add(new LoggerDTO(logger));
    }
    return loggers;
}
 
Example 11
Project: molgenis   File: CmdLineAnnotator.java View source code Vote up 6 votes
private static void configureLogging()
{
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

	PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
	patternLayoutEncoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
	patternLayoutEncoder.setContext(loggerContext);
	patternLayoutEncoder.start();

	ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
	consoleAppender.setContext(loggerContext);
	consoleAppender.setEncoder(patternLayoutEncoder);
	consoleAppender.setName("STDOUT");
	consoleAppender.start();

	Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.addAppender(consoleAppender);
	rootLogger.setLevel(Level.WARN);

	Logger molgenisLogger = (Logger) LoggerFactory.getLogger("org.molgenis");
	molgenisLogger.addAppender(consoleAppender);
	molgenisLogger.setLevel(Level.INFO);
	molgenisLogger.setAdditive(false);
}
 
Example 12
Project: MediaBrowser.Android   File: AppLogger.java View source code Vote up 6 votes
private static org.slf4j.Logger configureLogbackDirectly() {

        // reset the default context (which may already have been initialized)
        // since we want to reconfigure it
        LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
        lc.reset();

        // setup FileAppender
        PatternLayoutEncoder encoder1 = new PatternLayoutEncoder();
        encoder1.setContext(lc);
        encoder1.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
        encoder1.start();

        FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
        fileAppender.setContext(lc);
        fileAppender.setEncoder(encoder1);
        fileAppender.setName("fileAppender");
        fileAppender.setFile(getLogFilePath(""));
        fileAppender.addFilter(new LogFileFilter(false));
        fileAppender.start();

        syncServiceFileAppender = new FileAppender<ILoggingEvent>();
        syncServiceFileAppender.setContext(lc);
        syncServiceFileAppender.setEncoder(encoder1);
        syncServiceFileAppender.setName("syncServiceFileAppender");
        syncServiceFileAppender.addFilter(new LogFileFilter(true));

        LogcatAppender logcatAppender = new LogcatAppender();
        logcatAppender.setContext(lc);
        logcatAppender.setEncoder(encoder1);
        logcatAppender.setName("logcatAppender");
        logcatAppender.start();

        // add the newly created appenders to the root logger;
        // qualify Logger to disambiguate from org.slf4j.Logger
        ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.addAppender(fileAppender);
        root.addAppender(logcatAppender);
        root.addAppender(syncServiceFileAppender);

        return LoggerFactory.getLogger("App");
    }
 
Example 13
Project: spring-webmvc-dynamiclogging   File: MDCFilterController.java View source code Vote up 6 votes
@RequestMapping(value = "/1.0/admin/logging/mdc", method = RequestMethod.GET)
public @ResponseBody
Object getFilters()
{
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    for (TurboFilter filter : context.getTurboFilterList())
    {
        if (DynamicMDCFilter.class.equals(filter.getClass()))
        {
            return ((DynamicMDCFilter) filter).getRegisteredFilters();
        }
    }
    return "DynamicMDCFilter not configured.  Please check logback.xml.";
}
 
Example 14
Project: logback-flume   File: FlumeAppenderTest.java View source code Vote up 5 votes
@Test
public void testFlumeAppender() {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    		    
    PatternLayout layout = new PatternLayout();
    layout.setContext(loggerContext);
    layout.setPattern("%d{yyyy-MM-dd HH:mm:ss} %c [%p] %m%n");
    layout.start();

    FlumeAgent agent1 = new FlumeAgent("marshall.youmag.com", 4141);

    String type = "agent";
	int delay = 100;
	int agentRetries = 2;
	String name = "MyFlumeAppender";

	//		String dataDir = null;
	//		String dataDir = "InMemory";
	//		String excludes = null;
	//		String includes = null;
	//		String required = null;
	//		String mdcPrefix = null;
	//		String eventPrefix = null;
	//		boolean compressBody = false;
	//		int batchSize = 1;

	FlumeAppender fAppender = new FlumeAppender();

	fAppender.addAgent(agent1);
	fAppender.setType(type);
	fAppender.setReconnectDelay(delay);
	fAppender.setRetries(agentRetries);
	fAppender.setName(name);
	fAppender.setLayout(layout);

   	fAppender.setContext(loggerContext);

    fAppender.start();

    // attach the rolling file appender to the logger of your choice
    Logger logbackLogger = loggerContext.getLogger(FlumeAppenderTest.class);
    logbackLogger.addAppender(fAppender);
    
    // OPTIONAL: print logback internal status messages
    StatusPrinter.print(loggerContext);

    // log something
    logbackLogger.setLevel(Level.INFO);

    logbackLogger.debug("this is a debugggg message");

    logbackLogger.info("this is an info message");

    logbackLogger.error("this is an error message");
    
    // wait a bit.
    try {
		Thread.sleep(2000);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 15
Project: metrics   File: Main.java View source code Vote up 5 votes
/**
 * Entry point.
 *
 * @param args command line arguments
 */
public static void main(final String[] args) {
    LOGGER.info()
            .setMessage("Launching cluster-aggregator")
            .log();

    Thread.setDefaultUncaughtExceptionHandler(
            (thread, throwable) -> {
                System.err.println("Unhandled exception! exception: " + throwable.toString());
                throwable.printStackTrace(System.err);
            });

    Thread.currentThread().setUncaughtExceptionHandler(
            (thread, throwable) -> {
                LOGGER.error()
                        .setMessage("Unhandled exception!")
                        .setThrowable(throwable)
                        .log();
            }
    );

    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }

    LOGGER.debug()
            .setMessage("Loading configuration from file")
            .addData("file", args[0])
            .log();

    final File configurationFile = new File(args[0]);
    final Configurator<Main, ClusterAggregatorConfiguration> configurator =
            new Configurator<>(Main::new, ClusterAggregatorConfiguration.class);
    final ObjectMapper objectMapper = ClusterAggregatorConfiguration.createObjectMapper();
    final DynamicConfiguration configuration = new DynamicConfiguration.Builder()
            .setObjectMapper(objectMapper)
            .addSourceBuilder(
                    new JsonNodeFileSource.Builder().setObjectMapper(objectMapper)
                            .setFile(configurationFile))
            .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build())
            .addListener(configurator)
            .build();

    configuration.launch();

    Runtime.getRuntime().addShutdownHook(
            new Thread(
                    () -> {
                        configuration.shutdown();
                        configurator.shutdown();
                        LOGGER.info()
                                .setMessage("Stopping cluster-aggregator")
                                .log();
                        final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
                        context.stop();
                    }));
}