Java Code Examples for org.slf4j.Logger

The following are top voted examples for showing how to use org.slf4j.Logger. 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 generate more good examples.
Example 1
Project: lams   File: Signer.java   View source code 6 votes vote down vote up
/**
 * Signs a single XMLObject.
 * 
 * @param signature the signature to computer the signature on
 * @throws SignatureException thrown if there is an error computing the signature
 */
public static void signObject(Signature signature) throws SignatureException {
    Logger log = getLogger();
    try {
        XMLSignature xmlSignature = ((SignatureImpl) signature).getXMLSignature();

        if (xmlSignature == null) {
            log.error("Unable to compute signature, Signature XMLObject does not have the XMLSignature "
                    + "created during marshalling.");
            throw new SignatureException("XMLObject does not have an XMLSignature instance, unable to compute signature");
        }
        log.debug("Computing signature over XMLSignature object");
        xmlSignature.sign(SecurityHelper.extractSigningKey(signature.getSigningCredential()));
    } catch (XMLSecurityException e) {
        log.error("An error occured computing the digital signature", e);
        throw new SignatureException("Signature computation error", e);
    }
}
 
Example 2
Project: buenojo   File: ResourceHelper.java   View source code 6 votes vote down vote up
public static List<String> listWithoutPath(List<String> listWithPrefix, String fixedPath,  Logger log)
{
	final List<String> listWithoutFixedPath;
	listWithoutFixedPath= new ArrayList<String>();
	for (String resourcePath : listWithPrefix)
	{
		if (StringUtils.isNotEmpty(resourcePath))
			if (resourcePath.startsWith(fixedPath))
				listWithoutFixedPath.add(resourcePath.substring(fixedPath.length()));
			else
				log.warn(String.format("Invalid starting path %s, expected to begin with %s", resourcePath, fixedPath));
		else
			log.warn(String.format("Empty path %s", resourcePath));
	}
	return listWithoutFixedPath;
}
 
Example 3
Project: buenojo   File: ResourceHelper.java   View source code 6 votes vote down vote up
public static void validateResource(String resourcePath,Logger log) 
{ 

	ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
	try {
		if (resourceResolver.getResources("classpath*:/GameData" +resourcePath+"*").length==0)
			log.error("INEXISTENT RESOURCE "+"/GameData" +resourcePath+"*");
	} catch (IOException e) {
		// TODO Auto-generated catch block 
		e.printStackTrace();
	}
}
 
Example 4
Project: HuskyUI-Plugin   File: Metrics.java   View source code 6 votes vote down vote up
private JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) {
    JsonObject chart = new JsonObject();
    chart.addProperty("chartId", chartId);
    try {
        JsonObject data = getChartData();
        if (data == null) {
            // If the data is null we don't send the chart.
            return null;
        }
        chart.add("data", data);
    } catch (Throwable t) {
        if (logFailedRequests) {
            logger.warn("Failed to get data for custom chart with id {}", chartId, t);
        }
        return null;
    }
    return chart;
}
 
Example 5
Project: fresco_floodlight   File: ActionUtils.java   View source code 6 votes vote down vote up
/**
 * Parse set_vlan_id actions.
 * The key and delimiter for the action should be omitted, and only the
 * data should be presented to this decoder. Data with a leading 0x is permitted.
 * 
 * @param actionToDecode; The action as a string to decode
 * @param version; The OF version to create the action for
 * @param log
 * @return
 */
private static OFActionSetVlanVid decode_set_vlan_id(String actionToDecode, OFVersion version, Logger log) {
	Matcher n = Pattern.compile("((?:0x)?\\d+)").matcher(actionToDecode);
	if (n.matches()) {            
		if (n.group(1) != null) {
			try {
				VlanVid vlanid = VlanVid.ofVlan(get_short(n.group(1)));
				OFActionSetVlanVid.Builder ab = OFFactories.getFactory(version).actions().buildSetVlanVid();
				ab.setVlanVid(vlanid);
				log.debug("action {}", ab.build());
				return ab.build();
			}
			catch (NumberFormatException e) {
				log.debug("Invalid VLAN in: {} (error ignored)", actionToDecode);
				return null;
			}
		}          
	}
	else {
		log.debug("Invalid action: '{}'", actionToDecode);
		return null;
	}
	return null;
}
 
Example 6
Project: iTAP-controller   File: ActionUtils.java   View source code 6 votes vote down vote up
/**
 * Parse set_tos actions.
 * The key and delimiter for the action should be omitted, and only the
 * data should be presented to this decoder. A leading 0x is permitted.
 * 
 * @param actionToDecode; The action as a string to decode
 * @param version; The OF version to create the action for
 * @param log
 * @return
 */
private static OFActionSetNwTos decode_set_tos_bits(String actionToDecode, OFVersion version, Logger log) {
	Matcher n = Pattern.compile("((?:0x)?\\d+)").matcher(actionToDecode); 
	if (n.matches()) {
		if (n.group(1) != null) {
			try {
				byte tosbits = get_byte(n.group(1));
				OFActionSetNwTos.Builder ab = OFFactories.getFactory(version).actions().buildSetNwTos();
				ab.setNwTos(tosbits);
				log.debug("action {}", ab.build());
				return ab.build();
			}
			catch (NumberFormatException e) {
				log.debug("Invalid dst-port in: {} (error ignored)", actionToDecode);
				return null;
			}
		}
	}
	else {
		log.debug("Invalid action: '{}'", actionToDecode);
		return null;
	}
	return null;
}
 
Example 7
Project: hekate   File: NettyClientHandler.java   View source code 6 votes vote down vote up
public NettyClientHandler(String id, int epoch, String protocol, int affinity, T login, Integer connTimeout, long idleTimeout,
    Logger log, NettyMetricsSink metrics, NettyClient<T> client, NetworkClientCallback<T> callback) {
    this.log = log;
    this.id = id;
    this.epoch = epoch;
    this.protocol = protocol;
    this.affinity = affinity;
    this.login = login;
    this.idleTimeout = idleTimeout;
    this.connTimeout = connTimeout;
    this.metrics = metrics;
    this.client = client;
    this.callback = callback;

    this.debug = log.isDebugEnabled();
    this.trace = log.isTraceEnabled();

    hbOnFlush = future -> {
        hbFlushed = true;

        if (!future.isSuccess() && future.channel().isOpen()) {
            future.channel().pipeline().fireExceptionCaught(future.cause());
        }
    };
}
 
Example 8
Project: comdor   File: GithubStepsTestCase.java   View source code 6 votes vote down vote up
/**
 * GithubSteps logs the received comment and author and
 * executes the given steps.
 * @throws Exception If something goes wrong.
 */
@Test
public void logsAndExecutesSteps() throws Exception {
    final Command comment = Mockito.mock(Command.class);
    Mockito.when(comment.json()).thenReturn(
        Json.createObjectBuilder().add("body", "@comdor run").build()
    );
    Mockito.when(comment.author()).thenReturn("amihaiemil");
    final Step toExecute = Mockito.mock(Step.class);
    
    final Steps steps = new GithubSteps(toExecute, comment);
    
    final Log log = Mockito.mock(Log.class);
    final Logger slf4j = Mockito.mock(Logger.class);
    Mockito.when(log.logger()).thenReturn(slf4j);
    
    steps.perform(log);
    
    Mockito.verify(slf4j).info("Received command: @comdor run");
    Mockito.verify(slf4j).info("Author login: amihaiemil");
    Mockito.verify(toExecute).perform(comment, log);
}
 
Example 9
Project: OSWf-OSWorkflow-fork   File: OSWfLogging.java   View source code 6 votes vote down vote up
/** 
 *  Write out the state the all the history steps. 
 */

public static void logHistorySteps(Logger logger, long piid, OSWfEngine wfEngine) {
        
    List<Step> steps = wfEngine.getHistorySteps(piid);
    WorkflowDescriptor wfDescriptor = wfEngine.getWorkflowDescriptor(wfEngine.getWorkflowName(piid));

    if(steps.size() > 0) 
        for (Step step : steps) 
            logger.debug(String.format("History Step: %3d %-20s %s  ",   // %3s-%3s
                step.getStepId(),
                wfDescriptor.getStep(step.getStepId()).getName(),
                step.getStatus()
                // dateFormatter.format(step.getStartDate()),
                // dateFormatter.format(step.getFinishDate())
            ));
   else
        logger.debug("No available history steps");
}
 
Example 10
Project: PlugFace   File: AbstractPluginManager.java   View source code 6 votes vote down vote up
protected void pluginHealthCheck() {
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
        private final Logger CHECKLOGGER = LoggerFactory.getLogger(AbstractPluginManager.class);

        @Override
        public void run() {
            for (Plugin p : context.getPluginMap().values()) {
                if (p.getStatus().equals(PluginStatus.ERROR)) {
                    CHECKLOGGER.error("HEALTH CHECK - Plugin {} is in error.", p.getName());
                    p.disable();
                }
            }
        }
    }, 0, 1, TimeUnit.SECONDS);
}
 
Example 11
Project: dds-examples   File: Slf4jDdsLogger.java   View source code 6 votes vote down vote up
public static Slf4jDdsLogger createRegisterLogger() throws IOException {
  // create logger
  Slf4jDdsLogger slf4jDdsLogger = new Slf4jDdsLogger();

  // register logger
  com.rti.ndds.config.Logger.get_instance().set_output_device(slf4jDdsLogger);
  com.rti.ndds.config.Logger.get_instance().set_print_format(LogPrintFormat.NDDS_CONFIG_LOG_PRINT_FORMAT_TIMESTAMPED);

  // set log level
  if (LOGGER.isTraceEnabled()) {
    com.rti.ndds.config.Logger.get_instance().set_verbosity(LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
  } else if (LOGGER.isWarnEnabled()) {
    com.rti.ndds.config.Logger.get_instance().set_verbosity(LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_WARNING);
  } else if (LOGGER.isErrorEnabled()) {
    com.rti.ndds.config.Logger.get_instance().set_verbosity(LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_ERROR);
  }

  // return logger
  return slf4jDdsLogger;
}
 
Example 12
Project: dremio-oss   File: AutoCloseables.java   View source code 6 votes vote down vote up
public static void close(ThreadPoolExecutor executor, Logger logger) {
  executor.shutdown(); // Disable new tasks from being submitted
  try {
    // Wait a while for existing tasks to terminate
    if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
      executor.shutdownNow(); // Cancel currently executing tasks
      // Wait a while for tasks to respond to being cancelled
      if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
        logger.error("Pool did not terminate");
      }
    }
  } catch (InterruptedException ie) {
    logger.warn("Executor interrupted while awaiting termination");

    // (Re-)Cancel if current thread also interrupted
    executor.shutdownNow();
    // Preserve interrupt status
    Thread.currentThread().interrupt();
  }
}
 
Example 13
Project: OftenPorter   File: PortExecutor.java   View source code 6 votes vote down vote up
private void exParamDeal(WObject wObject, PorterOfFun porterOfFun, ParamDealt.FailedReason reason,
        boolean responseWhenException)
{
    Logger LOGGER = logger(wObject);
    JResponse jResponse = null;
    if (LOGGER.isDebugEnabled() || responseWhenException)
    {
        jResponse = toJResponse(reason, wObject);
        LOGGER.debug("{}:{}", wObject.url(), jResponse);
    }
    if (responseWhenException)
    {
        if (jResponse == null)
        {
            jResponse = toJResponse(reason, wObject);
        }
        doFinalWrite(wObject, porterOfFun, jResponse);
    }
    close(wObject);
}
 
Example 14
Project: Pixie   File: GUILabelingTool.java   View source code 6 votes vote down vote up
/**
 * The entry point of application.
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(GUILabelingTool.class);
    System.getProperty("java.library.path");

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(() -> {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            //  SplashScreen.startSplash()

            GUILabelingTool gui = new GUILabelingTool(logger);
            gui.setVisible(true);
            // for the first run, some special configuration have to be done
            gui.firstStartInitialization();

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            logger.error("Create and display form");
            logger.debug("Create and display form {}", ex);
        }
    });
}
 
Example 15
Project: VirtualTool   File: VirtualTool.java   View source code 6 votes vote down vote up
@Inject
public VirtualTool(@ConfigDir(sharedRoot = true) Path path, Logger logger, PluginContainer container) {
    this.dataDir = Sponge.getGame().getSavesDirectory().resolve(PluginData.id);
    this.pluginContainer = container;
    this.logger = new VTLogger(CText.get(CText.Colors.BLUE, 1, "V") + CText.get(CText.Colors.MAGENTA, 0, "T"));
    this.configdirpath = path.resolve(PluginData.id);
    this.backpackDir = Paths.get(this.getConfigPath().toString(), "backpacks");
    this.configfullpath = Paths.get(this.getConfigPath().toString(), "config.json");
    this.settings = new Settings();
}
 
Example 16
Project: java-lsf   File: LsfJobInfo.java   View source code 5 votes vote down vote up
public void setLsfJobStatus(String lsfJobStatus) {
    this.lsfJobStatus = lsfJobStatus;
    
    if ("PEND".equals(lsfJobStatus)) {
        setStatus(JobStatus.PENDING);
    }
    else if ("RUN".equals(lsfJobStatus)) {
        setStatus(JobStatus.RUNNING);
    }
    else if ("DONE".equals(lsfJobStatus)) {
        setStatus(JobStatus.DONE);
    }
    else if ("EXIT".equals(lsfJobStatus)) {
        setStatus(JobStatus.EXIT);
    }
    else if ("PSUSP".equals(lsfJobStatus)) {
        setStatus(JobStatus.SUSPENDED);
    }
    else if ("USUSP".equals(lsfJobStatus)) {
        setStatus(JobStatus.SUSPENDED);
    }
    else if ("SSUSP".equals(lsfJobStatus)) {
        setStatus(JobStatus.SUSPENDED);
    }
    else if ("UNKWN".equals(lsfJobStatus)) {
        setStatus(JobStatus.OTHER);
    }
    else {
        setStatus(JobStatus.OTHER);
        Logger log = LoggerFactory.getLogger(JobStatus.class);
        log.error("Unknown LSF job status: "+lsfJobStatus);
    }
}
 
Example 17
Project: nifi-registry   File: RunNiFiRegistry.java   View source code 5 votes vote down vote up
private boolean isProcessRunning(final String pid, final Logger logger) {
    try {
        // We use the "ps" command to check if the process is still running.
        final ProcessBuilder builder = new ProcessBuilder();

        builder.command("ps", "-p", pid);
        final Process proc = builder.start();

        // Look for the pid in the output of the 'ps' command.
        boolean running = false;
        String line;
        try (final InputStream in = proc.getInputStream();
             final Reader streamReader = new InputStreamReader(in);
             final BufferedReader reader = new BufferedReader(streamReader)) {

            while ((line = reader.readLine()) != null) {
                if (line.trim().startsWith(pid)) {
                    running = true;
                }
            }
        }

        // If output of the ps command had our PID, the process is running.
        if (running) {
            logger.debug("Process with PID {} is running", pid);
        } else {
            logger.debug("Process with PID {} is not running", pid);
        }

        return running;
    } catch (final IOException ioe) {
        System.err.println("Failed to determine if Process " + pid + " is running; assuming that it is not");
        return false;
    }
}
 
Example 18
Project: servicebuilder   File: LogUtil.java   View source code 5 votes vote down vote up
public static void doLog(String s, LogLevel logLevel, Logger logger) {
    switch (logLevel) {
        case ERROR: {
            logger.error(s);
            break;
        }

        case WARN: {
            logger.warn(s);
            break;
        }

        case INFO: {
            logger.info(s);
            break;
        }

        case DEBUG: {
            logger.debug(s);
            break;
        }

        case TRACE: {
            logger.trace(s);
            break;
        }

        default: {
            logger.error(s);
            break;
        }
    }
}
 
Example 19
Project: asura   File: DBSemaphore.java   View source code 5 votes vote down vote up
/**
 * Grants a lock on the identified resource to the calling thread (blocking
 * until it is available).
 * 
 * @return true if the lock was obtained.
 */
public boolean obtainLock(Connection conn, String lockName)
    throws LockException {

    lockName = lockName.intern();

    Logger log = getLog();
    
    if(log.isDebugEnabled()) {
        log.debug(
            "Lock '" + lockName + "' is desired by: "
                    + Thread.currentThread().getName());
    }
    if (!isLockOwner(conn, lockName)) {

        executeSQL(conn, lockName, expandedSQL);
        
        if(log.isDebugEnabled()) {
            log.debug(
                "Lock '" + lockName + "' given to: "
                        + Thread.currentThread().getName());
        }
        getThreadLocks().add(lockName);
        //getThreadLocksObtainer().put(lockName, new
        // Exception("Obtainer..."));
    } else if(log.isDebugEnabled()) {
        log.debug(
            "Lock '" + lockName + "' Is already owned by: "
                    + Thread.currentThread().getName());
    }

    return true;
}
 
Example 20
Project: Patterdale   File: Patterdale.java   View source code 5 votes vote down vote up
public Patterdale(PatterdaleRuntimeParameters runtimeParameters, Map<String, DBConnectionPool> connectionPools, TypeToProbeMapper typeToProbeMapper, Map<String, Probe> probesByName, Logger logger) {
    this.runtimeParameters = runtimeParameters;
    this.connectionPools = connectionPools;
    this.typeToProbeMapper = typeToProbeMapper;
    this.probesByName = probesByName;
    this.logger = logger;
}
 
Example 21
Project: Reer   File: OutputEventListenerBackedLoggerContext.java   View source code 5 votes vote down vote up
public Logger getLogger(String name) {
    Logger logger = loggers.get(name);
    if (logger != null) {
        return logger;
    }

    logger = loggers.putIfAbsent(name, new OutputEventListenerBackedLogger(name, this, timeProvider));
    return logger != null ? logger : loggers.get(name);
}
 
Example 22
Project: cloudwatch-logback-appender   File: CloudWatchAppenderRealTest.java   View source code 5 votes vote down vote up
@Ignore("Integration test to test going to cloudwatch")
@Test
public void test() throws InterruptedException {
	Logger logger = LoggerFactory.getLogger(getClass());
	logger.info("testing stuff");
	logger.error("Here's a throw", new RuntimeException(new Exception("test exception here")));
	Thread.sleep(1000);
	logger.info("more stuff");
	Thread.sleep(10000000);
}
 
Example 23
Project: cli-java   File: Utils.java   View source code 5 votes vote down vote up
/**
 * Set logging level to given value. If not explicitly
 * specified, default level is used from *logger* properties file.
 * (As of the time writing - simplelogger.properties is used as default.)
 * <p/>
 * NOTE: SLF4J is not capable of changing log levels programatically!
 * We have to change the System/File property of given underlying logger.
 *
 * @param logLevel logging level to be logger set to
 */
public static void setLogLevel(String logLevel) {
    org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("com.redhat.mqe.jms");
    Level level;
    switch (logLevel.toLowerCase()) {
        case "all":
            level = Level.ALL;
            break;
        case "trace":
            level = Level.TRACE;
            break;
        case "debug":
            level = Level.DEBUG;
            break;
        case "info":
            level = Level.INFO;
            break;
        case "warn":
            level = Level.WARN;
            break;
        case "error":
            level = Level.ERROR;
            break;
        case "fatal":
            level = Level.FATAL;
            break;
        case "off":
            level = Level.OFF;
            break;
        default:
            level = Level.INFO;
    }
    LogManager.getRootLogger().setLevel(level);
    logger.setLevel(level);
}
 
Example 24
Project: ts-benchmark   File: Test.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
	Logger log=LoggerFactory.getLogger(Test.class);
	log.info("nihao{},{}",'a','b');
	String sql="insert into book values(%s,%s,%s)";
	String format = String.format(sql, 1,2,"3");
	System.out.println(format);
}
 
Example 25
Project: ZooKeeper   File: ZooTrace.java   View source code 5 votes vote down vote up
static public void logQuorumPacket(Logger log, long mask,
        char direction, QuorumPacket qp)
{
    if (isTraceEnabled(log, mask)) { 
        logTraceMessage(log, mask, direction +
                " " + LearnerHandler.packetToString(qp));
     }
}
 
Example 26
Project: openNaEF   File: FlashWaveTelnetClient.java   View source code 5 votes vote down vote up
public String changeMode(String changingMode) throws IOException, ConsoleException {
    Logger log = LoggerFactory.getLogger(getClass());
    log.debug("mode-change: " + this.currentMode + " to " + changingMode);
    if (MODE_ENABLE.equals(currentMode) && changingMode.startsWith(MODE_CONFIG)) {
        sendln("config");
        currentMode = changingMode;
        return translate(receiveToPrompt());
    } else if (currentMode.startsWith(MODE_CONFIG) && changingMode.startsWith(MODE_ENABLE)) {
        sendln("exit");
        currentMode = changingMode;
        return translate(receiveToPrompt());
    } else {
        return "";
    }
}
 
Example 27
Project: nifi-registry   File: RunNiFiRegistry.java   View source code 5 votes vote down vote up
private void killProcessTree(final String pid, final Logger logger) throws IOException {
    logger.debug("Killing Process Tree for PID {}", pid);

    final List<String> children = getChildProcesses(pid);
    logger.debug("Children of PID {}: {}", new Object[]{pid, children});

    for (final String childPid : children) {
        killProcessTree(childPid, logger);
    }

    Runtime.getRuntime().exec(new String[]{"kill", "-9", pid});
}
 
Example 28
Project: launcher-backend   File: AbstractGitRepoStep.java   View source code 5 votes vote down vote up
private static void gitAddCommitAndPush(Git git, String gitUrl, UserDetails userDetails, File basedir, String message, String branch, String origin, Logger logger) throws GitAPIException {
    PersonIdent personIdent = userDetails.createPersonIdent();

    GitUtils.configureBranch(git, branch, origin, gitUrl);
    GitUtils.addDummyFileToEmptyFolders(basedir);
    logger.info("About to git commit and push to: " + gitUrl + " and remote name " + origin);
    int retryCount = 5;
    for (int i = retryCount; i > 0; i--) {
        if (i < retryCount) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
        try {
            GitUtils.doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, true);
            return;
        } catch (TransportException e) {
            if (i <= 1) {
                throw e;
            } else {
                logger.info("Caught a transport exception: " + e + " so retrying");
            }
        }
    }
}
 
Example 29
Project: Hydrograph   File: ExecutionTrackingLogger.java   View source code 5 votes vote down vote up
private Logger getNewLogger(String jobID,String fileLogLocation) {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

	FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
	fileAppender.setContext(loggerContext);
	fileAppender.setFile(fileLogLocation);
	
       /*SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>();
       triggeringPolicy.setMaxFileSize("10MB");
       triggeringPolicy.start();*/

       PatternLayoutEncoder encoder = new PatternLayoutEncoder();
       encoder.setContext(loggerContext);
       encoder.setPattern("%msg%n");
       encoder.start();
       
       fileAppender.setEncoder(encoder);
       fileAppender.start();

       // attach the rolling file appender to the logger of your choice
       Logger logbackLogger = loggerContext.getLogger(jobID);
       ((ch.qos.logback.classic.Logger) logbackLogger).addAppender(fileAppender);
       
       executionTrackingLoggers.put(jobID, logbackLogger);
       
	return logbackLogger;
}
 
Example 30
Project: TOSCAna   File: ExecutionDummyPlugin.java   View source code 5 votes vote down vote up
@Override
public void transform(TransformationContext transformation) throws Exception {
    Logger logger = transformation.getLogger(getClass());
    int i = 0;
    transformation.getPluginFileAccess().access("some-output-file").append("some transformation result").close();
    logger.info("Waiting 500ms until completion");
    while (!Thread.currentThread().isInterrupted() && i < 5) {
        Thread.sleep(100);
        i++;
    }
    if (failDuringExec) {
        logger.info("Throwing test exception");
        throw new InterruptedException("Test Exception");
    }
}
 
Example 31
Project: lams   File: DefaultBootstrap.java   View source code 5 votes vote down vote up
/**
 * Initializes the artifact factories for SAML 1 and SAML 2 artifacts.
 * 
 * @throws ConfigurationException thrown if there is a problem initializing the artifact factory
 */
protected static void initializeArtifactBuilderFactories() throws ConfigurationException {
    Logger log = getLogger();
    log.debug("Initializing SAML Artifact builder factories");
    Configuration.setSAML1ArtifactBuilderFactory(new SAML1ArtifactBuilderFactory());
    Configuration.setSAML2ArtifactBuilderFactory(new SAML2ArtifactBuilderFactory());
}
 
Example 32
Project: orange-mathoms-logging   File: LoggingTest.java   View source code 5 votes vote down vote up
@Test
public void test_logging() {
	Logger logger = LoggerFactory.getLogger(LoggingTest.class);
	logger.info("info logging");
	try {
		new MyClient().getTheThings();
	} catch(Exception e) {
		logger.error("error logging with stack", e);
	}
}
 
Example 33
Project: comdor   File: StarRepoTestCase.java   View source code 5 votes vote down vote up
/**
 * StarRepo can successfully star a given repository.
 * @throws Exception If something goes wrong.
 */
@Test
public void starsRepo() throws Exception {
    final Log log = Mockito.mock(Log.class);
    final Logger slf4j = Mockito.mock(Logger.class);
    Mockito.doNothing().when(slf4j).info(Mockito.anyString());
    Mockito.doThrow(
        new IllegalStateException("Unexpected error; test failed")
    ).when(slf4j).error(Mockito.anyString());
    Mockito.when(log.logger()).thenReturn(slf4j);

    final Github gh = new MkGithub("amihaiemil");
    final Repo repo =  gh.repos().create(
        new Repos.RepoCreate("amihaiemil.github.io", false)
    );
    final Command com = Mockito.mock(Command.class);
    final Issue issue = Mockito.mock(Issue.class);
    Mockito.when(issue.repo()).thenReturn(repo);
    Mockito.when(com.issue()).thenReturn(issue);
    
    final Step star = new StarRepo(Mockito.mock(Step.class));
    MatcherAssert.assertThat(
        com.issue().repo().stars().starred(),
        Matchers.is(false)
    );
    star.perform(com, log);
    MatcherAssert.assertThat(
        com.issue().repo().stars().starred(),
        Matchers.is(true)
    );
}
 
Example 34
Project: esup-ecandidat   File: MethodUtils.java   View source code 5 votes vote down vote up
/**
 * Valide un bean
 * 
 * @param bean
 * @throws CustomException
 */
public static <T> Boolean validateBean(T bean, Logger logger) {
	logger.debug(" ***VALIDATION*** : " + bean);
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<T>> constraintViolations = validator.validate(bean);
	if (constraintViolations != null && constraintViolations.size() > 0) {
		for (ConstraintViolation<?> violation : constraintViolations) {
			logger.debug(" *** " + violation.getPropertyPath().toString() + " : " + violation.getMessage());
		}
		return false;
	}
	return true;
}
 
Example 35
Project: ait-platform   File: AitLogger.java   View source code 5 votes vote down vote up
/**
 * debug
 * @param logger
 * @param message
 * @param params
 */

public static void debug(Logger logger, String message, Object... params) {
	
	if (logger.isDebugEnabled()) {
		logger.debug(message, params);
	}
}
 
Example 36
Project: openNaEF   File: CommandUtil.java   View source code 5 votes vote down vote up
public static void dumpChanges(CommandBuilder builder) {
    Logger log = LoggerFactory.getLogger(CommandUtil.class);
    StringBuilder sb = new StringBuilder();
    for (ChangeUnit unit : builder.getChangeUnits()) {
        if (sb.length() > 0) {
            sb.append(", ");
        }
        sb.append(unit.simpleToString());
    }
    log.debug("BuildResult: changed:" + builder.getClass().getSimpleName() + "\r\n" + sb.toString());
}
 
Example 37
Project: kraken   File: OutpuStreamLogAdapter.java   View source code 5 votes vote down vote up
/**
 * Creates the Logging instance to flush to the given logger.
 */
public OutpuStreamLogAdapter(final Logger log, final String logPrefix, final boolean flushOnLineBreak) throws IllegalArgumentException {
    this.logPrefix = logPrefix;
    this.flushOnLineBreak = flushOnLineBreak;
    if (log == null) {
        throw new IllegalArgumentException("Logger or log level must be not null");
    }
    this.log = log;
    curBufLength = DEFAULT_BUFFER_LENGTH;
    buf = new byte[curBufLength];
    count = 0;
}
 
Example 38
Project: dlface   File: AppInitializer.java   View source code 5 votes vote down vote up
/**
 * Redirect JUL from third-party libraries to SLF4J
 */
private void redirectJULtoSLF4J() {
    LOGGER.info("Redirecting JUL to SLF4J");
    LogManager.getLogManager().reset();
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();
    java.util.logging.Logger.getGlobal().setLevel(Level.FINEST);
}
 
Example 39
Project: cas-server-4.2.1   File: CasLoggerFactory.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>Attempts to find the <strong>real</strong> {@code Logger} instance that
 * is doing the heavy lifting and routes the request to an instance of
 * {@link CasDelegatingLogger}. The instance is cached by the logger name.</p>
 */
@Override
public Logger getLogger(final String name) {
    if (StringUtils.isBlank(name)) {
        return NOPLogger.NOP_LOGGER;
    }
    synchronized (loggerMap) {
        if (!loggerMap.containsKey(name)) {
            final Logger logger = getRealLoggerInstance(name);
            loggerMap.put(name, new CasDelegatingLogger(logger));
        }
        return loggerMap.get(name);
    }
}
 
Example 40
Project: asura   File: RAMJobStore.java   View source code 4 votes vote down vote up
protected Logger getLog() {
    return log;
}