Java Code Examples for ch.qos.logback.classic.joran.JoranConfigurator#setContext()

The following examples show how to use ch.qos.logback.classic.joran.JoranConfigurator#setContext() . 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: 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 2
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 3
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 4
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 5
Source File: TestConfig.java    From iot-mqtt with Apache License 2.0 5 votes vote down vote up
public TestConfig(String configPath) {
	super(configPath);
       LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
       JoranConfigurator configurator = new JoranConfigurator();
       configurator.setContext(lc);
       lc.reset();
       try {
		configurator.doConfigure(getLogBackXmlPath());
	} catch (JoranException e) {
		e.printStackTrace();
	}
}
 
Example 6
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 7
Source File: LogUtils.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
public static void setLoggingFromClassPath() throws IOException, JoranException {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    loggerContext.reset();
    JoranConfigurator configurator = new JoranConfigurator();
    try(InputStream configStream = new ClassPathResource("logback.xml").getInputStream()){
        configurator.setContext(loggerContext);
        configurator.doConfigure(configStream); // loads logback file
    }
}
 
Example 8
Source File: LoggingBootstrapTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
public void resetLogToOriginal() throws Exception {
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();

    final JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);
    configurator.doConfigure(this.getClass().getClassLoader().getResource("logback-test.xml"));
}
 
Example 9
Source File: MQAdminStartup.java    From RocketMQ-Master-analyze 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));

    // 初始化Logback
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
 
Example 10
Source File: LogbackTest.java    From rocketmq-read 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 11
Source File: LogbackTest.java    From DDMQ 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: LogbackTest.java    From rocketmq-4.3.0 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 13
Source File: Main.java    From digdag with Apache License 2.0 5 votes vote down vote up
private static void configureLogging(String level, String logPath)
{
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);
    context.reset();

    // logback uses system property to embed variables in XML file
    Level lv = Level.toLevel(level.toUpperCase(), Level.DEBUG);
    System.setProperty("digdag.log.level", lv.toString());

    String name;
    if (logPath.equals("-")) {
        if (System.console() != null) {
            name = "/digdag/cli/logback-color.xml";
        } else {
            name = "/digdag/cli/logback-console.xml";
        }
    } else {
        System.setProperty("digdag.log.path", logPath);
        name = "/digdag/cli/logback-file.xml";
    }
    try {
        configurator.doConfigure(Main.class.getResource(name));
    } catch (JoranException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 14
Source File: Start.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void load(String path) {
    try {
        File file = new File(path);
        if (!file.exists() || !file.isFile() || !file.canRead()) {
            return;
        }
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure(file);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}
 
Example 15
Source File: RedisAppenderTest.java    From logback-redis-appender with Apache License 2.0 5 votes vote down vote up
protected void configLogger(String loggerxml) {
	LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

	try {
		JoranConfigurator configurator = new JoranConfigurator();
		configurator.setContext(context);
		context.reset();
		configurator.doConfigure(this.getClass().getResourceAsStream(loggerxml));
	} catch (JoranException je) {
		// StatusPrinter will handle this
	}
	StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
 
Example 16
Source File: MyLoggerListenerTest.java    From ns4_frame with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) 
	{
		URL url = Thread.currentThread().getContextClassLoader().getResource("joran_test.xml");
		
		//加载配置文件 然后获取logger 打印日志
		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(url.getPath());
			
//			logger.info("哈哈哈哈");
			
		} catch (JoranException je) {
			// StatusPrinter will handle this
			je.printStackTrace();
			return;
		}
		
		logger.info("哈哈哈哈哈哈||{}",1111);
		
		
	}
 
Example 17
Source File: NamesrvStartup.java    From rocketmq-4.3.0 with Apache License 2.0 4 votes vote down vote up
public static NamesrvController createNamesrvController(String[] args) throws IOException, JoranException {
//        从系统文件中查询rocketmq版本,默认4.3.0
        System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
//        PackageConflictDetect.detectFastjson();

//        构建命令行操作的指令 =》
        Options options = ServerUtil.buildCommandlineOptions(new Options());
//        mqnamesrv 启动namesrv命令 =》
        commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
        if (null == commandLine) {
//            系统非正常退出,流程结束
            System.exit(-1);
            return null;
        }

//        解析配置文件 =》
        final NamesrvConfig namesrvConfig = new NamesrvConfig();
//        =》
        final NettyServerConfig nettyServerConfig = new NettyServerConfig();
//        设置 namesrv的服务端口
        nettyServerConfig.setListenPort(9876);
//        c 指定启动的时候加载配置文件
        if (commandLine.hasOption('c')) {
//            命令行启动指定配置文件,前面用c开头
            String file = commandLine.getOptionValue('c');
            if (file != null) {
                InputStream in = new BufferedInputStream(new FileInputStream(file));
                properties = new Properties();
                properties.load(in);
                MixAll.properties2Object(properties, namesrvConfig);
                MixAll.properties2Object(properties, nettyServerConfig);

//                设置命令行启动namesrv指定的配置文件路径
                namesrvConfig.setConfigStorePath(file);

                System.out.printf("load config properties file OK, %s%n", file);
                in.close();
            }
        }

//        打印namesrv的配置信息,命令行上面加p
        if (commandLine.hasOption('p')) {
            MixAll.printObjectProperties(null, namesrvConfig);
            MixAll.printObjectProperties(null, nettyServerConfig);
//            正常程序退出
            System.exit(0);
        }

//        把命令行属性解析成properties
        MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);

//        解析 ROCKETMQ_HOME 环境变量
        if (null == namesrvConfig.getRocketmqHome()) {
            System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV);
//            系统非正常退出
            System.exit(-2);
        }

        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
//        logback日志文件路径
        configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml");

        log = InternalLoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);

        MixAll.printObjectProperties(log, namesrvConfig);
        MixAll.printObjectProperties(log, nettyServerConfig);

//        创建namesrv控制器 =》
        final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);

        // remember all configs to prevent discard 把配置文件配置值的属性值注册到namesrv控制器
        controller.getConfiguration().registerConfig(properties);

        return controller;
    }
 
Example 18
Source File: FiltersrvStartup.java    From rocketmq-all-4.1.0-incubating 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 ShutdownHookThread(log, new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                controller.shutdown();
                return null;
            }
        }));

        return controller;
    } catch (Throwable e) {
        e.printStackTrace();
        System.exit(-1);
    }
    return null;
}
 
Example 19
Source File: ChatServer.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) {
        }
    }
    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("Failed to configure loggers, shutting down...", je);
    }
}
 
Example 20
Source File: ContextInitializer.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
void joranConfigureByResource(URL url) throws JoranException {
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(loggerContext);
    configurator.doConfigure(url);
}