/** * Package access for testing purposes. */ void init() { try { try { new ContextInitializer(defaultLoggerContext).autoConfig(); } catch (JoranException je) { Util.report("Failed to auto configure default logger context", je); } // logback-292 if(!StatusUtil.contextHasStatusListener(defaultLoggerContext)) { StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext); } contextSelectorBinder.init(defaultLoggerContext, KEY); initialized = true; } catch (Throwable t) { // we should never get here Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t); } }
private void init() { String originalLogbackConfigFileValue = System.getProperty(ContextInitializer.CONFIG_FILE_PROPERTY); System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, findURLOfDefaultConfigurationFile()); System.setProperty(GREENPEPPER_DEBUG_SYSPROP, Boolean.toString(GreenPepper.isDebugEnabled())); // Logback initialisation try { Class<?> loggerBinderClass = Class.forName(LOGGER_BINDER_CLASSNAME); Method getSingletonMethod = loggerBinderClass.getMethod("getSingleton"); internalLoggerBinder = (LoggerFactoryBinder) getSingletonMethod.invoke(null); } catch (Exception e) { System.err.print("Unable to instanciate the LoggerFactoryBinder: " + e.getMessage()); throw new IllegalStateException("Wrong configuration of greenpepper logger.", e); } if (StringUtils.isNotBlank(originalLogbackConfigFileValue)) { System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, originalLogbackConfigFileValue); } else { System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); } System.clearProperty(GREENPEPPER_DEBUG_SYSPROP); }
public static Logger getLogger(String name) { Logger askedLogger; if (!initialized) { synchronized (GreenPepperLogger.class) { String originalLogbackConfigFileValue = System.getProperty(ContextInitializer.CONFIG_FILE_PROPERTY); System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "greenpepper-logback.xml"); System.setProperty(GREENPEPPER_DEBUG_SYSPROP, Boolean.toString(GreenPepper.isDebugEnabled())); askedLogger = LoggerFactory.getLogger(name); if (StringUtils.isNotBlank(originalLogbackConfigFileValue)) { System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, originalLogbackConfigFileValue); } else { System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); } System.clearProperty(GREENPEPPER_DEBUG_SYSPROP); initialized = true; } } else { askedLogger = LoggerFactory.getLogger(name); } return askedLogger; }
private void configureLogger() { // Check if SLF4J is bound to logback in the current environment ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (!(loggerFactory instanceof LoggerContext)) { return; } LoggerContext context = (LoggerContext) loggerFactory; context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try { File twillLogback = new File(Constants.Files.LOGBACK_TEMPLATE); if (twillLogback.exists()) { configurator.doConfigure(twillLogback); } new ContextInitializer(context).autoConfig(); } catch (JoranException e) { throw Throwables.propagate(e); } doConfigure(configurator, getLogConfig(getLoggerLevel(context.getLogger(Logger.ROOT_LOGGER_NAME)))); }
@Before public void beforeResetLogging() { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); ContextInitializer ci = new ContextInitializer(loggerContext); URL url = ci.findURLOfDefaultConfigurationFile(true); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); loggerContext.reset(); configurator.doConfigure(url); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); }
/** * 在日志中记录一些系统信息 */ public static void logSystemProperties(String[] args) { log.info("java.version = {}; os = {}, {}, {}", System.getProperty("java.version"), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")); Runtime runtime = Runtime.getRuntime(); log.info("processors = {}; jvm.heap = {}/{}M; file.encoding = {}", runtime.availableProcessors(), runtime.totalMemory() / 0x100000, runtime.maxMemory() / 0x100000, System.getProperty("file.encoding")); log.info("user.name = {}; user.dir = {}", System.getProperty("user.name"), System.getProperty("user.dir")); log.info("java.class.path = {}", System.getProperty("java.class.path")); URL url = new ContextInitializer(logCtx).findURLOfDefaultConfigurationFile(true); if(url == null) throw new Error("not found logback.xml from classpath"); log.info("logback.path = {}", url.getPath()); if(args != null) { for(int i = 0, n = args.length; i < n; ++i) log.info("arg{} = {}", i, args[i]); } }
@PreAuthorize("hasAnyRole('ROLE_SU')") @PostMapping("/loggers/reset") @ResponseStatus(HttpStatus.OK) public void resetLoggers() { ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory(); if (!(iLoggerFactory instanceof LoggerContext)) { throw new RuntimeException("Logger factory is not a Logback logger context"); } LoggerContext loggerContext = (LoggerContext) iLoggerFactory; ContextInitializer ci = new ContextInitializer(loggerContext); URL url = ci.findURLOfDefaultConfigurationFile(true); loggerContext.reset(); try { ci.configureByResource(url); } catch (JoranException e) { LOG.error("Error reloading log configuration", e); throw new RuntimeException(e); } }
/** * Package access for testing purposes. */ void init() { try { try { new ContextInitializer(defaultLoggerContext).autoConfig(); } catch (JoranException je) { Util.report("Failed to auto configure default logger context", je); } StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext); contextSelectorBinder.init(defaultLoggerContext, KEY); initialized = true; } catch (Throwable t) { // we should never get here Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t); } }
public static void adjustDetailedTracing(SystemProperties config, long blockNum) { // here we can turn on the detail tracing in the middle of the chain if (blockNum >= config.traceStartBlock() && config.traceStartBlock() != -1) { final URL configFile = ClassLoader.getSystemResource("logback-detailed.xml"); final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); final ContextInitializer ci = new ContextInitializer(loggerContext); loggerContext.reset(); try { ci.configureByResource(configFile); } catch (Exception e) { System.out.println("Error applying new config " + e.getMessage()); } } }
private void configureLogger() throws MalformedURLException, JoranException { // Check if SLF4J is bound to logback in the current environment ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (!(loggerFactory instanceof LoggerContext)) { return; } LoggerContext context = (LoggerContext) loggerFactory; ContextInitializer contextInitializer = new ContextInitializer(context); URL url = contextInitializer.findURLOfDefaultConfigurationFile(false); if (url == null) { // The logger context was not initialized using configuration file, initialize it with the logback template. File twillLogback = new File(Constants.Files.RUNTIME_CONFIG_JAR, Constants.Files.LOGBACK_TEMPLATE); if (twillLogback.exists()) { contextInitializer.configureByResource(twillLogback.toURI().toURL()); } } // Attach the KafkaAppender to the root logger KafkaAppender kafkaAppender = new KafkaAppender(); kafkaAppender.setName("KAFKA"); kafkaAppender.setTopic(Constants.LOG_TOPIC); kafkaAppender.setHostname(getHostname()); // The Kafka ZK Connection shouldn't be null as this method only get called if log collection is enabled kafkaAppender.setZookeeper(getTwillRuntimeSpecification().getKafkaZKConnect()); String runnableName = getRunnableName(); if (runnableName != null) { kafkaAppender.setRunnableName(runnableName); } kafkaAppender.setContext(context); kafkaAppender.start(); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(kafkaAppender); }
private void configureByResourceUrl( LoggingInitializationContext initializationContext, LoggerContext loggerContext, URL url) throws JoranException { if (url.toString().endsWith("xml")) { JoranConfigurator configurator = new SpringBootJoranConfigurator( initializationContext); configurator.setContext(loggerContext); configurator.doConfigure(url); } else { new ContextInitializer(loggerContext).configureByResource(url); } }
/** * 自定义加载日志文件,初始化日志框架 * @param logbackUrl 日志配置文件路径 * @throws FileNotFoundException * @throws JoranException */ protected void locate(String logbackUrl) throws FileNotFoundException, JoranException { if(Strings.isBlank(logbackUrl)) return; logbackUrl = (logbackUrl = logbackUrl.trim()).startsWith(CLASS_PREFIX) ? logbackUrl : CLASS_PREFIX + logbackUrl; URL url = ResourceUtils.getURL(logbackUrl); LoggerContext loggerContext = (LoggerContext)StaticLoggerBinder.getSingleton().getLoggerFactory(); loggerContext.reset(); new ContextInitializer(loggerContext).configureByResource(url); }
static public void main(String[] args) throws Exception { if (args.length < 2) { usage("Wrong number of arguments."); } String qcfBindingName = args[0]; String queueBindingName = args[1]; String username = null; String password = null; if (args.length == 4) { username = args[2]; password = args[3]; } LoggerContext loggerContext = (LoggerContext) LoggerFactory .getILoggerFactory(); new ContextInitializer(loggerContext).autoConfig(); new JMSQueueSink(qcfBindingName, queueBindingName, username, password); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JMSQueueSink."); while (true) { String s = stdin.readLine(); if (s.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); return; } } }
static public void main(String[] args) throws Exception { if (args.length < 2) { usage("Wrong number of arguments."); } String tcfBindingName = args[0]; String topicBindingName = args[1]; String username = null; String password = null; if (args.length == 4) { username = args[2]; password = args[3]; } LoggerContext loggerContext = (LoggerContext) LoggerFactory .getILoggerFactory(); new ContextInitializer(loggerContext).autoConfig(); new JMSTopicSink(tcfBindingName, topicBindingName, username, password); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JMSTopicSink."); while (true) { String s = stdin.readLine(); if (s.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); return; } } }
@Test public void noOutputIfContextHasAStatusListener() { System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, ClassicTestConstants.INPUT_PREFIX + "issue/logback292.xml"); System.setProperty(ContextInitializer.STATUS_LISTENER_CLASS, NopStatusListener.class.getName()); StaticLoggerBinderFriend.reset(); assertEquals(0, tee.baos.size()); }
@Before public void setUp() throws Exception { System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "recursiveInit.xml"); StaticLoggerBinderFriend.reset(); LoggerFactoryFriend.reset(); }
public static void overrideLogging() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); ContextInitializer initializer = new ContextInitializer(context); try { initializer.autoConfig(); } catch (JoranException ignored) {} }
@After public void tearDown() throws Exception { logger.detachAppender(appender); loggerContext.stop(); ContextInitializer logInitializer = new ContextInitializer(loggerContext); logInitializer.autoConfig(); loggerContext.start(); }
public static void configureLogback(Object rawContext) { if (rawContext instanceof LoggerContext) { LoggerContext context = (LoggerContext)rawContext; ContextInitializer initializer = new ContextInitializer(context); if (initializer.findURLOfDefaultConfigurationFile(false) == null) { context.reset(); URL defaultConfig = context.getClass().getClassLoader().getResource("logback-default.xml"); try { initializer.configureByResource(defaultConfig); } catch (JoranException e) { throw new RuntimeException("Failed to load default logging configuration", e); } } } }
@Test public void testSuccesfullyMessage() throws JoranException, InterruptedException, ExecutionException, UnsupportedEncodingException { Future<String> future = ExecutorServiceUtil.newExecutorService().submit(this.task); LoggerContext context = new LoggerContext(); new ContextInitializer(context).configureByResource(getClass().getResource("/SplunkUdpSocketAppenderTest-logback.xml")); String logLineMultiplied = createLogLineMultiplied("geub", UdpSocketOutputStream.UDP_MAX_LENGTH_IN_BYTES / 4); context.getLogger(getClass()).info(logLineMultiplied); Assert.assertEquals("Wrong value", logLineMultiplied, future.get()); Assert.assertEquals(UdpSocketOutputStream.UDP_MAX_LENGTH_IN_BYTES, getBytesLength(logLineMultiplied)); }
@Test public void testSuccesfullyTruncateMessage() throws JoranException, InterruptedException, ExecutionException, UnsupportedEncodingException { Future<String> future = ExecutorServiceUtil.newExecutorService().submit(this.task); LoggerContext context = new LoggerContext(); new ContextInitializer(context).configureByResource(getClass().getResource("/SplunkUdpSocketAppenderTest-logback.xml")); String logLineMultiplied = createLogLineMultiplied("geub", UdpSocketOutputStream.UDP_MAX_LENGTH_IN_BYTES); context.getLogger(getClass()).info(logLineMultiplied); Assert.assertEquals("Wrong value", createLogLineMultiplied("geub", UdpSocketOutputStream.UDP_MAX_LENGTH_IN_BYTES / 4), future.get()); Assert.assertEquals(UdpSocketOutputStream.UDP_MAX_LENGTH_IN_BYTES, getBytesLength(future.get())); }
@Test public void testSuccesfullySendMessage() throws JoranException, InterruptedException, ExecutionException { Future<String> future = ExecutorServiceUtil.newExecutorService().submit(this.task); LoggerContext context = new LoggerContext(); new ContextInitializer(context).configureByResource(getClass().getResource("/SplunkTcpSocketAppenderTest-logback.xml")); String uuid = UUID.randomUUID().toString(); context.getLogger(getClass()).info(uuid); context.stop(); Assert.assertEquals("Valor do log incorreto", uuid, future.get()); }
@Test public void testSuccesfullySendMessage() throws JoranException, InterruptedException, ExecutionException { Future<String> future = ExecutorServiceUtil.newExecutorService().submit(this.task); LoggerContext context = new LoggerContext(); new ContextInitializer(context).configureByResource(getClass().getResource("/SplunkUdpSocketAppenderTest-logback.xml")); String uuid = UUID.randomUUID().toString(); context.getLogger(getClass()).info(uuid); Assert.assertEquals("Wrong value", uuid, future.get()); }
public void reloadDefaultConfiguration() throws JoranException { ContextInitializer ci = new ContextInitializer(loggerContext); URL url = ci.findURLOfDefaultConfigurationFile(true); reloadByURL(url); }
public LoggerContext getLoggerContext() { String contextName = null; Context ctx = null; // First check if ThreadLocal has been set already LoggerContext lc = threadLocal.get(); if (lc != null) { return lc; } try { // We first try to find the name of our // environment's LoggerContext ctx = JNDIUtil.getInitialContext(); contextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME); } catch (NamingException ne) { // We can't log here } if (contextName == null) { // We return the default context return defaultContext; } else { // Let's see if we already know such a context LoggerContext loggerContext = synchronizedContextMap.get(contextName); if (loggerContext == null) { // We have to create a new LoggerContext loggerContext = new LoggerContext(); loggerContext.setName(contextName); synchronizedContextMap.put(contextName, loggerContext); URL url = findConfigFileURL(ctx, loggerContext); if (url != null) { configureLoggerContextByURL(loggerContext, url); } else { try { new ContextInitializer(loggerContext).autoConfig(); } catch (JoranException je) { } } // logback-292 if (!StatusUtil.contextHasStatusListener(loggerContext)) StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } return loggerContext; } }
@After public void tearDown() { System.setOut(original); System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); System.clearProperty(ContextInitializer.STATUS_LISTENER_CLASS); }
@After public void tearDown() throws Exception { System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); }
@BeforeClass public static void beforeClass() { // Robolectric somehow prevents logback from grabbing assets, // so tell logback to look in a specific location System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "assets/logback.xml"); }
@AfterClass public static void afterClass() { System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); }
public LoggerContext getLoggerContext() { //System.out.println("getLoggerContext request"); // First check if ThreadLocal has been set already LoggerContext lc = threadLocal.get(); if (lc != null) { //System.out.printf("Thread local found: %s\n", lc.getName()); return lc; } if (contextName == null) { //System.out.println("Context name was null, returning default"); // We return the default context return defaultContext; } else { // Let's see if we already know such a context LoggerContext loggerContext = contextMap.get(contextName); //System.out.printf("Logger context for %s is %s\n", contextName, loggerContext); if (loggerContext == null) { // We have to create a new LoggerContext loggerContext = new LoggerContext(); loggerContext.setName(contextName); // allow override using logbacks system prop String overrideProperty = System.getProperty("logback.configurationFile"); if (overrideProperty == null) { contextConfigFile = String.format("logback-%s.xml", contextName); } else { contextConfigFile = String.format(overrideProperty, contextName); } System.out.printf("Context logger config file: %s\n", contextConfigFile); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); //System.out.printf("Thread context cl: %s\n", classloader); //ClassLoader classloader2 = Loader.class.getClassLoader(); //System.out.printf("Loader tcl: %s\n", classloader2); //URL url = Loader.getResourceBySelfClassLoader(contextConfigFile); URL url = Loader.getResource(contextConfigFile, classloader); if (url != null) { try { JoranConfigurator configurator = new JoranConfigurator(); loggerContext.reset(); configurator.setContext(loggerContext); configurator.doConfigure(url); } catch (JoranException e) { StatusPrinter.print(loggerContext); } } else { try { ContextInitializer ctxInit = new ContextInitializer(loggerContext); ctxInit.autoConfig(); } catch (JoranException je) { StatusPrinter.print(loggerContext); } } System.out.printf("Adding logger context: %s to map for context: %s\n", loggerContext.getName(), contextName); contextMap.put(contextName, loggerContext); } return loggerContext; } }