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

The following examples show how to use ch.qos.logback.classic.LoggerContext#start() . 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: LOGBackConfigurer.java    From styx with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize LOGBack from the given URL.
 *
 * @param url              the url pointing to the location of the config file.
 * @param installJULBridge set to true to install SLF4J JUL bridge
 * @throws IllegalArgumentException if the url points to a non existing location or an error occurs during the parsing operation.
 */
public static void initLogging(URL url, boolean installJULBridge) {
    StaticLoggerBinder.getSingleton();
    ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
    LoggerContext loggerContext = selector.getLoggerContext();
    loggerContext.stop();
    ContextInitializer ctxi = new ContextInitializer(loggerContext);
    try {
        ctxi.configureByResource(url);
        loggerContext.start();
        if (installJULBridge) {
            //uninstall already present handlers we want to
            //continue logging through SLF4J after this point
            Logger l = LogManager.getLogManager().getLogger("");
            for (Handler h : l.getHandlers()) {
                l.removeHandler(h);
            }
            SLF4JBridgeHandler.install();

        }
    } catch (JoranException e) {
        throw new IllegalArgumentException("exception while initializing LOGBack", e);
    }
}
 
Example 2
Source File: AbstractLocalDevBimServerStarter.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add a file appender to every logger we can find (the loggers should already have been configured via logback.xml)
 * 
 * @throws IOException
 */
private void fixLogging(BimServerConfig config) throws IOException {
	Path logFolder = config.getHomeDir().resolve("logs");
	if (!Files.isDirectory(logFolder)) {
		Files.createDirectories(logFolder);
	}
	Path file = logFolder.resolve("bimserver.log");

	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	PatternLayoutEncoder ple = new PatternLayoutEncoder();

	ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
	ple.setContext(lc);
	ple.start();
	FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
	String filename = file.toAbsolutePath().toString();

	if (lc instanceof LoggerContext) {
	    if (!lc.isStarted()) {
	    	lc.start();
	    }
	}
	
	System.out.println("Logging to " + filename);
	
	fileAppender.setFile(filename);
	fileAppender.setEncoder(ple);
	fileAppender.setContext(lc);
	fileAppender.start();

	for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
		if (log.getLevel() != null) {
			log.addAppender(fileAppender);
		}
	}
}
 
Example 3
Source File: JarBimServer.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add a file appender to every logger we can find (the loggers should already have been configured via logback.xml)
 * 
 * @throws IOException
 */
private void fixLogging(BimServerConfig config) throws IOException {
	Path logFolder = config.getHomeDir().resolve("logs");
	if (!Files.isDirectory(logFolder)) {
		Files.createDirectories(logFolder);
	}
	Path file = logFolder.resolve("bimserver.log");

	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	PatternLayoutEncoder ple = new PatternLayoutEncoder();

	ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
	ple.setContext(lc);
	ple.start();
	FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
	String filename = file.toAbsolutePath().toString();

	if (lc instanceof LoggerContext) {
	    if (!lc.isStarted()) {
	    	lc.start();
	    }
	}
	
	System.out.println("Logging to " + filename);
	
	fileAppender.setFile(filename);
	fileAppender.setEncoder(ple);
	fileAppender.setContext(lc);
	fileAppender.start();

	for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
		if (log.getLevel() != null) {
			log.addAppender(fileAppender);
		}
	}
}
 
Example 4
Source File: WarServerInitializer.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add a file appender to every logger we can find (the loggers should already have been configured via logback.xml)
 * 
 * @throws IOException
 */
private void fixLogging(BimServerConfig config) throws IOException {
	Path logFolder = config.getHomeDir().resolve("logs");
	if (!Files.isDirectory(logFolder)) {
		Files.createDirectories(logFolder);
	}
	Path file = logFolder.resolve("bimserver.log");

	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	PatternLayoutEncoder ple = new PatternLayoutEncoder();

	ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
	ple.setContext(lc);
	ple.start();
	FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
	String filename = file.toAbsolutePath().toString();

	if (lc instanceof LoggerContext) {
	    if (!lc.isStarted()) {
	    	lc.start();
	    }
	}
	
	System.out.println("Logging to " + filename);
	
	fileAppender.setFile(filename);
	fileAppender.setEncoder(ple);
	fileAppender.setContext(lc);
	fileAppender.start();

	for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
		if (log.getLevel() != null) {
			log.addAppender(fileAppender);
		}
	}
}
 
Example 5
Source File: MapAppenderUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    ctx = new LoggerContext();
    ctx.setName("test context");
    ctx.setStatusManager(new BasicStatusManager());
    mapAppender.setContext(ctx);
    mapAppender.setPrefix("prefix");
    event = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.INFO, "Test message for logback appender", null, new Object[0]);
    ctx.start();
}
 
Example 6
Source File: NsLog.java    From ns4_frame with Apache License 2.0 4 votes vote down vote up
private static void renameLoggingFile() {
     LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
     context.stop();
     context.reset();
     JoranConfigurator configurator = new JoranConfigurator();
     configurator.setContext(context);
     try {
         URL url = getResource(LogConstants.AUTOCONFIG_FILE, Thread.currentThread().getContextClassLoader());
         if (url == null) {
             throw new RuntimeException("init Log error,can't find logback.xml");
         }
         
         
         System.out.println("初始化File:"+url.getFile());
         
         
         configurator.doConfigure(url.getFile());
     } catch (JoranException e) {
     	
     	//读取文件读不到 读取流
     	try {
	configurator.doConfigure(getResourceAsStream(LogConstants.AUTOCONFIG_FILE, Thread.currentThread().getContextClassLoader()));
} catch (JoranException e1) {
	throw new RuntimeException(e.getMessage(), e1);
}
     	
     }

     String configFile = System.getProperty("configfile");
     if(configFile == null || "".equals(configFile)) {
     	configFile = "";
     	//System.out.println("ns_log.configfile is null");
     }else {
     	configFile = configFile.indexOf(".") != -1 ? configFile.substring(0, configFile.lastIndexOf(".")) : configFile;
     	configFile += "_";
     	//System.out.println("ns_log.configfile is configFile");
     }
     
     for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
         Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders();
         while (index.hasNext()) {
             Appender<ILoggingEvent> appender = index.next();
             if (appender instanceof NSLogRollingFileAppender) {
                 NSLogRollingFileAppender fileAppender = ((NSLogRollingFileAppender) appender);
                 fileAppender.stop();
                 String fileName = fileAppender.getFile().replace("configfile_", configFile);
                 fileAppender.setFile(fileName);
                 //System.out.println("ns_log.filenNme:" + fileName);

                 TriggeringPolicy triggeringPolicy = fileAppender.getTriggeringPolicy();
                 if (triggeringPolicy instanceof TimeBasedRollingPolicy) {
                     TimeBasedRollingPolicy timeBasedRollingPolicy = ((TimeBasedRollingPolicy) triggeringPolicy);
                     String fileNamePattern = timeBasedRollingPolicy.getFileNamePattern().replace("configfile_", configFile);
                     timeBasedRollingPolicy.setFileNamePattern(fileNamePattern);
                     //System.out.println("ns_log.fileNamePattern:" + fileNamePattern);
                     timeBasedRollingPolicy.stop();
                     timeBasedRollingPolicy.start();
                 }
                 fileAppender.realStart();
             }
         }
     }
     context.start();
 }
 
Example 7
Source File: SingularityExecutorLogging.java    From Singularity with Apache License 2.0 4 votes vote down vote up
public Logger buildTaskLogger(
  String taskId,
  String executorId,
  String executorPid,
  String taskLogFile
) {
  LOG.info("Building a task logger for {} pointing to {}", taskId, taskLogFile);

  LoggerContext context = new LoggerContext();

  context.setName(executorPid);

  baseLogging.prepareRootLogger(context);

  String loggerId = taskId;

  try {
    SingularityTaskId singularityTaskId = SingularityTaskId.valueOf(taskId);

    loggerId =
      String.format(
        "%s.%s.%s.%s.%s",
        singularityTaskId.getRequestId(),
        singularityTaskId.getDeployId(),
        singularityTaskId.getStartedAt(),
        singularityTaskId.getInstanceNo(),
        executorId
      );
  } catch (InvalidSingularityTaskIdException e) {
    LOG.info("Handling non-SingularityTaskId %s", taskId);
  }

  Logger taskLogger = context.getLogger(loggerId);
  taskLogger.detachAndStopAllAppenders();

  if (baseLogging.getRootLogPath().isPresent()) {
    taskLogger.addAppender(
      baseLogging.buildFileAppender(context, baseLogging.getRootLogPath().get())
    );
  }
  taskLogger.addAppender(baseLogging.buildFileAppender(context, taskLogFile));

  context.start();

  return taskLogger;
}