Java Code Examples for ch.qos.logback.classic.LoggerContext#reset()

The following examples show how to use ch.qos.logback.classic.LoggerContext#reset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ITestApplication.java    From camel-spring-boot with Apache License 2.0 7 votes vote down vote up
private static void overrideLoggingConfig() {

        URL logbackFile = ITestApplication.class.getResource("/spring-logback.xml");
        if (logbackFile != null) {

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

            try {
                JoranConfigurator configurator = new JoranConfigurator();
                configurator.setContext(context);
                // Call context.reset() to clear any previous configuration, e.g. default
                // configuration. For multi-step configuration, omit calling context.reset().
                context.reset();
                configurator.doConfigure(logbackFile);
            } catch (JoranException je) {
                // StatusPrinter will handle this
            }
            StatusPrinter.printInCaseOfErrorsOrWarnings(context);
        }

    }
 
Example 2
Source File: LogbackLoggingConfigurer.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doFailSafeConfiguration() {
    // Not really fail-safe, just less likely to fail
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.setLevel(Level.INFO);

    ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
    rootLogger.addAppender(appender);
    appender.setContext(context);
    appender.setTarget("System.err");

    PatternLayout layout = new PatternLayout();
    appender.setLayout(layout);
    layout.setPattern("%msg%n%ex");
    layout.setContext(context);

    layout.start();
    appender.start();
}
 
Example 3
Source File: LogbackConfiguration.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void load() throws IOException {
	try {
		if (System.getProperty(LOGGING_DIR_PROPERTY) == null) {
			System.setProperty(LOGGING_DIR_PROPERTY, getLoggingDir().getAbsolutePath());
		}
	} catch (SecurityException e) {
		System.out.println("Not allowed to read or write system property '" + LOGGING_DIR_PROPERTY + "'");
	}

	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	try {
		configurator = new LogConfigurator();
		configurator.setContext(lc);
		lc.reset();
		configurator.doConfigure(configFile);
	} catch (JoranException je) {
		System.out.println("Logback configuration error");
		je.printStackTrace();
		StatusPrinter.print(lc);
	}
}
 
Example 4
Source File: LogbackLoggingConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void doConfigure(LogLevel logLevel) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);

    if (currentLevel == null) {
        context.reset();
        context.addTurboFilter(new GradleFilter());
        context.getLogger("org.apache.http.wire").setLevel(Level.OFF);
        context.getLogger("org.codehaus.groovy.runtime.m12n.MetaInfExtensionModule").setLevel(Level.ERROR);
        GradleAppender appender = new GradleAppender();
        appender.setContext(context);
        appender.start();
        rootLogger.addAppender(appender);
    }

    currentLevel = logLevel;
    rootLogger.setLevel(LogLevelConverter.toLogbackLevel(logLevel));
}
 
Example 5
Source File: LogbackController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @return The list of log levels configured and their settings
 */
@RequestMapping(value = "reset", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> reset() {
    final LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
    synchronized (ctx) {
        File configuration = ConfigurationWatchListUtil.getConfigurationWatchList(ctx).getCopyOfFileWatchList().get(0);
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(ctx);
        ctx.reset();
        try {
            configurator.doConfigure(configuration);
        } catch (JoranException e) {
            log.error("Error re-applying the configuration");
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 6
Source File: LogbackConfiguratorListener.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    // 从web.xml中加载指定文件名的日志配置文件
    String logbackConfigLocation = event.getServletContext().getInitParameter(CONFIG_LOCATION);
    InputStream fn = event.getClass().getClassLoader().getResourceAsStream(logbackConfigLocation);
    if (fn == null) {
        return;
    }
    try {
        LoggerContext loggerContext = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();
        loggerContext.reset();
        JoranConfigurator joranConfigurator = new JoranConfigurator();
        joranConfigurator.setContext(loggerContext);
        joranConfigurator.doConfigure(fn);
        logger.debug("loaded slf4j configure file from " + fn);
    } catch (JoranException e) {
        logger.error("can loading slf4j configure file from " + fn, e);
    }
}
 
Example 7
Source File: Syslog4jAppenderTest.java    From logback-syslog4j with MIT License 6 votes vote down vote up
public void testTcpSender() throws JoranException, InterruptedException {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);
    context.reset();
    configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-tcp.xml"));

    Logger logger = context.getLogger("test-tcp");
    logger.info("test message over tcp");

    context.stop();
    Thread.sleep(100);

    final String serverData = serverStream.toString();
    assertTrue("Server received: " + serverData, serverData.contains("test message over tcp"));
}
 
Example 8
Source File: Global.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
private static void setupLogback() {
	LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
	Logger.info("Setting up Logback");
	Logger.info("Application running from: {}", Start.getApplicationDirectory().getAbsolutePath());
	System.setProperty("application.home", Start.getApplicationDirectory().getAbsolutePath());
	File xmlConfig = new File(new File(Start.getApplicationDirectory(), "conf"), "application-logger.xml");
	if (xmlConfig.exists()) {
		try {
			JoranConfigurator configurator = new JoranConfigurator();
			configurator.setContext(context);
			context.reset();
			configurator.doConfigure(xmlConfig);
		} catch (JoranException je) {
			// StatusPrinter will handle this
		}
	}
	//System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO, Logger.underlying()), true));
	System.setErr(new PrintStream(new LoggerOutputStream(Level.OFF, Logger.underlying()), true));
	Logger.info("Logback Setup");
	StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
 
Example 9
Source File: App.java    From PeerWasp with MIT License 6 votes vote down vote up
/**
 * Initializes the logging framework.
 * The automatic configuration is reset and the logger is configured dynamically:
 * - The log folder is set
 * - The log configuration is loaded (not from resources, but from the working directory).
 *
 * This allows switching the folder and the configuration during development and at deployment.
 */
private void initializeLogging() {
	LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
	try {
		JoranConfigurator jc = new JoranConfigurator();
		jc.setContext(context);
		// override default configuration
		context.reset();
		// inject the location of the appdata log folder as "LOG_FOLDER"
		// property of the LoggerContext
		context.putProperty("LOG_FOLDER", AppData.getLogFolder().toString());
		jc.doConfigure(LOG_CONFIGURATION);
	} catch (JoranException je) {
		// status printer will handle printing of error
	}
	StatusPrinter.printInCaseOfErrorsOrWarnings(context);
	logger.debug("Initialized logging (LOG_FOLDER={})", context.getProperty("LOG_FOLDER"));
}
 
Example 10
Source File: MQAdminStartup.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private static void initLogback() throws JoranException {
    String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
 
Example 11
Source File: LogbackTest.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws JoranException {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
 
Example 12
Source File: LoggingConfigurator.java    From logging-java with Apache License 2.0 5 votes vote down vote up
/**
 * Configure logging using a logback configuration file.
 *
 * @param file         A logback configuration file.
 * @param defaultIdent Fallback logging identity, used if not specified in config file.
 */
public static void configure(final File file, final String defaultIdent) {
  final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

  // Setup context
  final LoggerContext context = rootLogger.getLoggerContext();
  context.reset();

  // Log uncaught exceptions
  UncaughtExceptionLogger.setDefaultUncaughtExceptionHandler();

  // Load logging configuration from file
  try {
    final JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);
    configurator.doConfigure(file);
  } catch (JoranException je) {
    // StatusPrinter will handle this
  }

  context.putProperty("pid", getMyPid());
  final String hostname = getSpotifyHostname();
  if (hostname != null) {
    context.putProperty("hostname", hostname);
  }

  final String ident = context.getProperty("ident");
  if (ident == null) {
    context.putProperty("ident", defaultIdent);
  }

  StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
 
Example 13
Source File: BaseCommand.java    From emissary with Apache License 2.0 5 votes vote down vote up
private void doLogbackReinit(LoggerContext loggerContext, String configFilePath) {
    System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, configFilePath);
    loggerContext.reset();
    ContextInitializer newContext = new ContextInitializer(loggerContext);
    try {
        newContext.autoConfig();
    } catch (JoranException e) {
        LOG.error("Problem reconfiguring logback with {}", getLogbackConfig(), e);
    }
}
 
Example 14
Source File: BookstoreLogger.java    From spring-data-rest-acl with Apache License 2.0 5 votes vote down vote up
private void init() {
	JoranConfigurator configurator = new JoranConfigurator();
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
       configurator.setContext(loggerContext);
       loggerContext.reset();
       try {
		configurator.doConfigure(logbackconfig);
	} catch (JoranException e) {
		// StatusPrinter will handle this
	}
       StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
       
       logger.info("Test Log");		
       logger.error("error msg");
}
 
Example 15
Source File: MQAdminStartup.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
private static void initLogback() throws JoranException {
    String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
 
Example 16
Source File: MQAdminStartup.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
private static void initLogback() throws JoranException {
    String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
 
Example 17
Source File: LogzioLogbackAppenderTest.java    From logzio-logback-appender with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextReset() {
    logger.info("context.reset() is called when logback loads a new logback.xml in-flight");
    String token = "testingContextReset";
    String type = "contextResetType" + random(8);
    String loggerName = "ContextResetLogger" + random(8);
    int drainTimeout = 1;

    String message1 = "Before Reset Line - "+random(5);
    String message2 = "After Reset Line - "+random(5);

    Logger testLogger = createLogger(logzioLogbackAppender, token, type, loggerName, drainTimeout, false, false, null, false);

    testLogger.info(message1);
    sleepSeconds(2 * drainTimeout);

    mockListener.assertNumberOfReceivedMsgs(1);
    MockLogzioBulkListener.LogRequest logRequest = mockListener.assertLogReceivedByMessage(message1);
    mockListener.assertLogReceivedIs(logRequest, token, type, loggerName, Level.INFO.levelStr);

    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    // This clears everything from the context
    loggerContext.reset();

    // We need to add the appender again
    testLogger = createLogger(logzioLogbackAppender, token, type, loggerName, drainTimeout, false, false, null, false);

    testLogger.warn(message2);
    sleepSeconds(2 * drainTimeout);

    mockListener.assertNumberOfReceivedMsgs(2);
    logRequest = mockListener.assertLogReceivedByMessage(message2);
    mockListener.assertLogReceivedIs(logRequest, token, type, loggerName, Level.WARN.levelStr);
}
 
Example 18
Source File: LogModule.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {

    // Only load logback configuration if GUACAMOLE_HOME exists
    File guacamoleHome = environment.getGuacamoleHome();
    if (!guacamoleHome.isDirectory())
        return;

    // Check for custom logback.xml
    File logbackConfiguration = new File(guacamoleHome, "logback.xml");
    if (!logbackConfiguration.exists())
        return;

    logger.info("Loading logback configuration from \"{}\".", logbackConfiguration);

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

    try {

        // Initialize logback
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        configurator.doConfigure(logbackConfiguration);

        // Dump any errors that occur during logback init
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);

    }
    catch (JoranException e) {
        logger.error("Initialization of logback failed: {}", e.getMessage());
        logger.debug("Unable to load logback configuration..", e);
    }

}
 
Example 19
Source File: GameServer.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
private static void initalizeLoggger() {
	new File("./log/backup/").mkdirs();
	File[] files = new File("log").listFiles(new FilenameFilter() {

		@Override
		public boolean accept(File dir, String name) {
			return name.endsWith(".log");
		}
	});

	if (files != null && files.length > 0) {
		byte[] buf = new byte[1024];
		try {
			String outFilename = "./log/backup/" + new SimpleDateFormat("yyyy-MM-dd HHmmss").format(new Date()) + ".zip";
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
			out.setMethod(ZipOutputStream.DEFLATED);
			out.setLevel(Deflater.BEST_COMPRESSION);

			for (File logFile : files) {
				FileInputStream in = new FileInputStream(logFile);
				out.putNextEntry(new ZipEntry(logFile.getName()));
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
				logFile.delete();
			}
			out.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	try {
		JoranConfigurator configurator = new JoranConfigurator();
		configurator.setContext(lc);
		lc.reset();
		configurator.doConfigure("config/slf4j-logback.xml");
	}
	catch (JoranException je) {
		throw new RuntimeException("[LoggerFactory] Failed to configure loggers, shutting down...", je);
	}
}
 
Example 20
Source File: FiltersrvStartup.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
public static FiltersrvController createController(String[] args) {
    System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));

    if (null == System.getProperty(NettySystemConfig.COM_ROCKETMQ_REMOTING_SOCKET_SNDBUF_SIZE)) {
        NettySystemConfig.socketSndbufSize = 65535;
    }

    if (null == System.getProperty(NettySystemConfig.COM_ROCKETMQ_REMOTING_SOCKET_RCVBUF_SIZE)) {
        NettySystemConfig.socketRcvbufSize = 1024;
    }

    try {
        Options options = ServerUtil.buildCommandlineOptions(new Options());
        final CommandLine commandLine =
            ServerUtil.parseCmdLine("mqfiltersrv", args, buildCommandlineOptions(options),
                new PosixParser());
        if (null == commandLine) {
            System.exit(-1);
            return null;
        }

        final FiltersrvConfig filtersrvConfig = new FiltersrvConfig();
        final NettyServerConfig nettyServerConfig = new NettyServerConfig();

        if (commandLine.hasOption('c')) {
            String file = commandLine.getOptionValue('c');
            if (file != null) {
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                Properties properties = new Properties();
                properties.load(in);
                MixAll.properties2Object(properties, filtersrvConfig);
                System.out.printf("load config properties file OK, " + file + "%n");
                in.close();

                String port = properties.getProperty("listenPort");
                if (port != null) {
                    filtersrvConfig.setConnectWhichBroker(String.format("127.0.0.1:%s", port));
                }
            }
        }

        nettyServerConfig.setListenPort(0);
        nettyServerConfig.setServerAsyncSemaphoreValue(filtersrvConfig.getFsServerAsyncSemaphoreValue());
        nettyServerConfig.setServerCallbackExecutorThreads(filtersrvConfig
            .getFsServerCallbackExecutorThreads());
        nettyServerConfig.setServerWorkerThreads(filtersrvConfig.getFsServerWorkerThreads());

        if (commandLine.hasOption('p')) {
            MixAll.printObjectProperties(null, filtersrvConfig);
            MixAll.printObjectProperties(null, nettyServerConfig);
            System.exit(0);
        }

        MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), filtersrvConfig);
        if (null == filtersrvConfig.getRocketmqHome()) {
            System.out.printf("Please set the " + MixAll.ROCKETMQ_HOME_ENV
                + " variable in your environment to match the location of the RocketMQ installation%n");
            System.exit(-2);
        }

        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure(filtersrvConfig.getRocketmqHome() + "/conf/logback_filtersrv.xml");
        log = LoggerFactory.getLogger(LoggerName.FILTERSRV_LOGGER_NAME);

        final FiltersrvController controller =
            new FiltersrvController(filtersrvConfig, nettyServerConfig);
        boolean initResult = controller.initialize();
        if (!initResult) {
            controller.shutdown();
            System.exit(-3);
        }

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            private volatile boolean hasShutdown = false;
            private AtomicInteger shutdownTimes = new AtomicInteger(0);

            @Override
            public void run() {
                synchronized (this) {
                    log.info("shutdown hook was invoked, " + this.shutdownTimes.incrementAndGet());
                    if (!this.hasShutdown) {
                        this.hasShutdown = true;
                        long begineTime = System.currentTimeMillis();
                        controller.shutdown();
                        long consumingTimeTotal = System.currentTimeMillis() - begineTime;
                        log.info("shutdown hook over, consuming time total(ms): " + consumingTimeTotal);
                    }
                }
            }
        }, "ShutdownHook"));

        return controller;
    } catch (Throwable e) {
        e.printStackTrace();
        System.exit(-1);
    }
    return null;
}