org.apache.commons.logging.Log Java Examples

The following examples show how to use org.apache.commons.logging.Log. 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: EsHiveInputFormat.java    From elasticsearch-hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public FileSplit[] getSplits(JobConf job, int numSplits) throws IOException {
    // first, merge input table properties (since there's no access to them ...)
    Settings settings = HadoopSettingsManager.loadFrom(job);
    //settings.merge(IOUtils.propsFromString(settings.getProperty(HiveConstants.INPUT_TBL_PROPERTIES)));

    Log log = LogFactory.getLog(getClass());
    // move on to initialization
    InitializationUtils.setValueReaderIfNotSet(settings, HiveValueReader.class, log);
    InitializationUtils.setUserProviderIfNotSet(settings, HadoopUserProvider.class, log);
    if (settings.getOutputAsJson() == false) {
        // Only set the fields if we aren't asking for raw JSON
        settings.setProperty(InternalConfigurationOptions.INTERNAL_ES_TARGET_FIELDS, StringUtils.concatenate(HiveUtils.columnToAlias(settings), ","));
    }

    HiveUtils.init(settings, log);

    // decorate original splits as FileSplit
    InputSplit[] shardSplits = super.getSplits(job, numSplits);
    FileSplit[] wrappers = new FileSplit[shardSplits.length];
    Path path = new Path(job.get(HiveConstants.TABLE_LOCATION));
    for (int i = 0; i < wrappers.length; i++) {
        wrappers[i] = new EsHiveSplit(shardSplits[i], path);
    }
    return wrappers;
}
 
Example #2
Source File: StreamPumper.java    From big-c with Apache License 2.0 6 votes vote down vote up
StreamPumper(final Log log, final String logPrefix,
    final InputStream stream, final StreamType type) {
  this.log = log;
  this.logPrefix = logPrefix;
  this.stream = stream;
  this.type = type;
  
  thread = new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        pump();
      } catch (Throwable t) {
        ShellCommandFencer.LOG.warn(logPrefix +
            ": Unable to pump output from " + type,
            t);
      }
    }
  }, logPrefix + ": StreamPumper for " + type);
  thread.setDaemon(true);
}
 
Example #3
Source File: IOUtils.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Try to close an IO resource and log and return if there was an exception.
 *  
 * <p>An exception is only returned if the IOException passed in is null.
 * 
 * @param closeable to be closed
 * @param logger the logger to be used so that logging appears under that log instance
 * @param resourceName the name to appear in the log output
 * @param initialException if set, this exception will be returned even where there is another
 * exception while closing the IO resource * @return the IOException is there was any but only
 * if initialException is null
 */
public static IOException closeAndLogException(Closeable closeable, Log logger, String resourceName, IOException initialException)
{
    try
    {
        closeable.close();
    }
    catch (IOException ioe)
    {
        logger.warn("Error closing " + resourceName, ioe);
        if (initialException == null)
        {
            return ioe;
        }
    }
    return initialException;
}
 
Example #4
Source File: LogUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Print {@link WebSocketFrame} information.
 *
 * @param log              {@link Log} object of the relevant class
 * @param frame            {@link WebSocketFrame} frame
 * @param channelContextId {@link ChannelHandlerContext} context id as a String
 * @param customMsg        Log message which needs to be appended to the frame information,
 *                         if it is not required provide null
 * @param isInbound        true if the frame is inbound, false if it is outbound
 */
private static void printWebSocketFrame(
        Log log, WebSocketFrame frame, String channelContextId,
        String customMsg, boolean isInbound) {

    String logStatement = getDirectionString(isInbound) + channelContextId;
    if (frame instanceof PingWebSocketFrame) {
        logStatement += " Ping frame";
    } else if (frame instanceof PongWebSocketFrame) {
        logStatement += " Pong frame";
    } else if (frame instanceof CloseWebSocketFrame) {
        logStatement += " Close frame";
    } else if (frame instanceof BinaryWebSocketFrame) {
        logStatement += " Binary frame";
    } else if (frame instanceof TextWebSocketFrame) {
        logStatement += " " + ((TextWebSocketFrame) frame).text();
    }

    //specifically for logging close websocket frames with error status
    if (customMsg != null) {
        logStatement += " " + customMsg;
    }
    log.debug(logStatement);

}
 
Example #5
Source File: SimpleApplicationEventMulticaster.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
	try {
		listener.onApplicationEvent(event);
	}
	catch (ClassCastException ex) {
		String msg = ex.getMessage();
		if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
			// Possibly a lambda-defined listener which we could not resolve the generic event type for
			// -> let's suppress the exception and just log a debug message.
			Log logger = LogFactory.getLog(getClass());
			if (logger.isTraceEnabled()) {
				logger.trace("Non-matching event type for listener: " + listener, ex);
			}
		}
		else {
			throw ex;
		}
	}
}
 
Example #6
Source File: MyPerformanceMonitorInterceptor.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log log) throws Throwable {
    
    String name = createInvocationTraceName(invocation);
    long start = System.currentTimeMillis();
    log.info("Method "+name+" execution started at:"+new Date());
    try {
        return invocation.proceed();
    }
    finally {
        long end = System.currentTimeMillis();
        long time = end - start;
        log.info("Method "+name+" execution lasted:"+time+" ms");
        log.info("Method "+name+" execution ended at:"+new Date());
        
        if (time > 10){
            log.warn("Method execution longer than 10 ms!");
        }
        
    }
}
 
Example #7
Source File: CustomPerformanceMonitorInterceptor.java    From Hands-On-High-Performance-with-Spring-5 with MIT License 6 votes vote down vote up
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log log) 
  throws Throwable {
    String name = createInvocationTraceName(invocation);
    long start = System.currentTimeMillis();
    log.info("Method " + name + " execution started at:" + new Date());
    try {
        return invocation.proceed();
    }
    finally {
        long end = System.currentTimeMillis();
        long time = end - start;
        log.info("Method "+name+" execution lasted:"+time+" ms");
        log.info("Method "+name+" execution ended at:"+new Date());
         
        if (time > 5){
            log.warn("Method execution took longer than 5 ms!");
        } 
    }
}
 
Example #8
Source File: InstructionSet.java    From QLExpress with Apache License 2.0 6 votes vote down vote up
public void executeInnerOrigiInstruction(RunEnvironment environmen,List<String> errorList,Log aLog) throws Exception{
		Instruction instruction =null;
	try {
		while (environmen.programPoint < this.instructionList.length) {
			QLExpressTimer.assertTimeOut();
			instruction = this.instructionList[environmen.programPoint];
			instruction.setLog(aLog);// 设置log
			instruction.execute(environmen, errorList);
		}
	} catch (Exception e) {
		if (printInstructionError) {
			log.error("当前ProgramPoint = " + environmen.programPoint);
			log.error("当前指令" + instruction);
			log.error(e);
		}
		throw e;
	}
}
 
Example #9
Source File: CodeStyleTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that only static loggers exist.
 */
private void staticLoggers(final List<String> lines, final String relativePath) {
    int i = 0;
    final String logClassName = Log.class.getSimpleName();
    for (String line : lines) {
        line = line.trim();
        if (line.contains(" " + logClassName + " ") && !line.contains(" LOG ") && !line.contains(" static ")
            && !line.startsWith("//") && !line.contains("httpclient.wire")) {
            addFailure("Non-static logger in " + relativePath + ", line: " + (i + 1));
        }
        i++;
    }
}
 
Example #10
Source File: TestConfigurationLogger.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether info logging is possible.
 */
@Test
public void testInfo()
{
    final Log log = EasyMock.createMock(Log.class);
    log.info(MSG);
    EasyMock.replay(log);
    final ConfigurationLogger logger = new ConfigurationLogger(log);

    logger.info(MSG);
    EasyMock.verify(log);
}
 
Example #11
Source File: WorkflowFormPersister.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public WorkflowFormPersister(ContentModelItemData<?> itemData,
            NamespaceService namespaceService,
            DictionaryService dictionaryService,
            WorkflowService workflowService,
            NodeService nodeService,
            BehaviourFilter behaviourFilter, Log logger)
{
    super(itemData, namespaceService, dictionaryService, logger);
    WorkflowDefinition definition = (WorkflowDefinition) itemData.getItem();
    this.builder = new WorkflowBuilder(definition, workflowService, nodeService, behaviourFilter);
}
 
Example #12
Source File: InitializationUtils.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
public static boolean setUserProviderIfNotSet(Settings settings, Class<? extends UserProvider> clazz, Log log) {
    if (!StringUtils.hasText(settings.getSecurityUserProviderClass())) {
        settings.setProperty(ConfigurationOptions.ES_SECURITY_USER_PROVIDER_CLASS, clazz.getName());
        Log logger = (log != null ? log : LogFactory.getLog(clazz));
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Using pre-defined user provider [%s] as default", settings.getSecurityUserProviderClass()));
        }
        return true;
    }
    return false;
}
 
Example #13
Source File: Log4jWebConfigurerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void assertLogOutput() {
	Log log = LogFactory.getLog(this.getClass());
	log.debug("debug");
	log.info("info");
	log.warn("warn");
	log.error("error");
	log.fatal("fatal");

	assertTrue(MockLog4jAppender.loggingStrings.contains("debug"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("info"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("warn"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("error"));
	assertTrue(MockLog4jAppender.loggingStrings.contains("fatal"));
}
 
Example #14
Source File: AliasedLoggingCommand.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public CommandResult execute(Object[] params) {

        try {
            Log logger = LogFactory.getLog(this.getClass().getName());
            if (logger instanceof org.openas2.logging.Log) {
                return execute(logger, params);
            }
            // Add support for other logging packages here as necessary
            return new CommandResult(CommandResult.TYPE_COMMAND_NOT_SUPPORTED, "Not supported by current logging factory");
        } catch (OpenAS2Exception oae) {
            oae.terminate();

            return new CommandResult(oae);
        }
    }
 
Example #15
Source File: PluginRules.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a List of all registered Rule instances that match the specified
 * nodepath, or a zero-length List if there are no matches.  If more
 * than one Rule instance matches, they <strong>must</strong> be returned
 * in the order originally registered through the <code>add()</code>
 * method.
 * <p>
 * @param namespaceURI Namespace URI for which to select matching rules,
 *  or <code>null</code> to match regardless of namespace URI
 * @param path the path to the xml nodes to be matched.
 */
public List<Rule> match(String namespaceURI, String path) {
    Log log = LogUtils.getLogger(digester);
    boolean debug = log.isDebugEnabled();
    
    if (debug) {
        log.debug(
            "Matching path [" + path +
            "] on rules object " + this.toString());
    }

    List<Rule> matches;
    if ((mountPoint != null) && 
        (path.length() <= mountPoint.length())) {
        if (debug) {
            log.debug(
                "Path [" + path + "] delegated to parent.");
        }
        
        matches = parent.match(namespaceURI, path);
        
        // Note that in the case where path equals mountPoint, 
        // we deliberately return only the rules from the parent,
        // even though this object may hold some rules matching
        // this same path. See PluginCreateRule's begin, body and end
        // methods for the reason.
    } else {
            log.debug("delegating to decorated rules.");
        matches = decoratedRules.match(namespaceURI, path); 
    }

    return matches;
}
 
Example #16
Source File: InstructionCallSelfDefineFunction.java    From QLExpress with Apache License 2.0 5 votes vote down vote up
public static OperateData executeSelfFunction(RunEnvironment environment,InstructionSet functionSet,
		ArraySwap parameters,List<String> errorList,Log log)throws Exception{	
	InstructionSetContext  context = OperateDataCacheManager.fetchInstructionSetContext (
			true,environment.getContext().getExpressRunner(),environment.getContext(),environment.getContext().getExpressLoader(),environment.getContext().isSupportDynamicFieldName());
	OperateDataLocalVar[] vars = functionSet.getParameters();
	for(int i=0;i<vars.length;i++){
		//注意此处必须new 一个新的对象,否则就会在多次调用的时候导致数据冲突
		OperateDataLocalVar var = OperateDataCacheManager.fetchOperateDataLocalVar(vars[i].getName(),vars[i].getOrgiType());
		context.addSymbol(var.getName(), var);
		var.setObject(context, parameters.get(i).getObject(environment.getContext()));
	}
	Object result =InstructionSetRunner.execute((InstructionSet)functionSet,
			context,errorList,environment.isTrace(),false,true,log);
	return OperateDataCacheManager.fetchOperateData(result,null);
}
 
Example #17
Source File: DefaultFieldBuilder.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public DefaultFieldBuilder(FormCreationData formData,
            FieldProcessorRegistry registry,
            NamespaceService namespaceService,
            List<String> ignoredFields,
            Log logger)
{
    this.logger = logger;
    this.formData = formData;
    this.registry = registry;
    this.namespaceService = namespaceService;
    this.ignoredFields = getNonNullList(ignoredFields );
    this.ItemData = (ContentModelItemData<?>) formData.getItemData();
}
 
Example #18
Source File: CommonsLoggerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTrace() {
    Log mockLog = mock(Log.class);

    InternalLogger logger = new CommonsLogger(mockLog, "foo");
    logger.trace("a");

    verify(mockLog).trace("a");
}
 
Example #19
Source File: CustomizableTraceInterceptorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testSunnyDayPathLogsCorrectly() throws Throwable {

	MethodInvocation methodInvocation = mock(MethodInvocation.class);
	given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString"));
	given(methodInvocation.getThis()).willReturn(this);

	Log log = mock(Log.class);
	given(log.isTraceEnabled()).willReturn(true);

	CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
	interceptor.invoke(methodInvocation);

	verify(log, times(2)).trace(anyString());
}
 
Example #20
Source File: RestService.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a RestRepository for use with a multi-index resource pattern. The client is left pinned
 * to the original node that it was pinned to since the shard locations cannot be determined at all.
 * @param settings Job settings
 * @param currentInstance Partition number
 * @param resource Configured write resource
 * @param log Logger to use
 * @return The RestRepository to be used by the partition writer
 */
private static RestRepository initMultiIndices(Settings settings, long currentInstance, Resource resource, Log log) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Resource [%s] resolves as an index pattern", resource));
    }

    // multi-index write - since we don't know before hand what index will be used, use an already selected node
    String node = SettingsUtils.getPinnedNode(settings);
    if (log.isDebugEnabled()) {
        log.debug(String.format("Partition writer instance [%s] assigned to [%s]", currentInstance, node));
    }

    return new RestRepository(settings);
}
 
Example #21
Source File: HeartBeat.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
HeartBeat(final Progressable progressable, Configuration cfg, TimeValue lead, final Log log) {
    Assert.notNull(progressable, "a valid progressable is required to report status to Hadoop");
    TimeValue tv = HadoopCfgUtils.getTaskTimeout(cfg);

    Assert.isTrue(tv.getSeconds() <= 0 || tv.getSeconds() > lead.getSeconds(), "Hadoop timeout is shorter than the heartbeat");

    this.progressable = progressable;
    long cfgMillis = (tv.getMillis() > 0 ? tv.getMillis() : 0);
    // the task is simple hence the delay = timeout - lead, that is when to start the notification right before the timeout
    this.delay = new TimeValue(Math.abs(cfgMillis - lead.getMillis()), TimeUnit.MILLISECONDS);
    this.log = log;

    String taskId;
    TaskID taskID = HadoopCfgUtils.getTaskID(cfg);

    if (taskID == null) {
        log.warn("Cannot determine task id...");
        taskId = "<unknown>";
        if (log.isTraceEnabled()) {
            log.trace("Current configuration is " + HadoopCfgUtils.asProperties(cfg));
        }
    }
    else {
        taskId = "" + taskID;
    }

    id = taskId;
}
 
Example #22
Source File: ConfigurationEndpointUtils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static NotFoundException buildNotFoundRequestException(String description, String code,
                                                              Log log, Throwable e) {

    ErrorDTO errorDTO = getErrorDTO(ConfigurationConstants.STATUS_NOT_FOUND_MESSAGE_DEFAULT, description, code);
    logDebug(log, e);
    return new NotFoundException(errorDTO);
}
 
Example #23
Source File: CommonsLoggerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsErrorEnabled() {
    Log mockLog = mock(Log.class);

    when(mockLog.isErrorEnabled()).thenReturn(true);

    InternalLogger logger = new CommonsLogger(mockLog, "foo");
    assertTrue(logger.isErrorEnabled());

    verify(mockLog).isErrorEnabled();
}
 
Example #24
Source File: CompilationMessageCollector.java    From spork with Apache License 2.0 5 votes vote down vote up
private static void logMessage(String messageString, MessageType messageType, Log log) {
    switch(messageType) {
    case Info:
        log.info(messageString);
        break;
    case Warning:
        log.warn(messageString);
        break;
    case Error:
        log.error(messageString);
    }
}
 
Example #25
Source File: CommonsLoggingListener.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.api.AuditListener */
public void addException(AuditEvent aEvt, Throwable aThrowable)
{
    if (mInitialized) {
        final Log log = mLogFactory.getInstance(aEvt.getSourceName());
        log.error("Error auditing " + aEvt.getFileName(), aThrowable);
    }
}
 
Example #26
Source File: IOUtils.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
/**
 * Close the Closeable objects and <b>ignore</b> any {@link IOException} or 
 * null pointers. Must only be used for cleanup in exception handlers.
 * @param log the log to record problems to at debug level. Can be null.
 * @param closeables the objects to close
 */
public static void cleanup(Log log, java.io.Closeable... closeables) {
  for(java.io.Closeable c : closeables) {
    if (c != null) {
      try {
        c.close();
      } catch(IOException e) {
        if (log != null && log.isDebugEnabled()) {
          log.debug("Exception in closing " + c, e);
        }
      }
    }
  }
}
 
Example #27
Source File: LogUtil.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Print the headers associated with the initial Http Response.
 * The header details will be printed in the following format.
 * <p>
 * " >> Headers [channelContextId] [header name] : [header value]"
 *
 * @param log {@link Log} object of the relevant class
 * @param msg {@link FullHttpResponse} response from the backend
 * @param ctx {@link ChannelHandlerContext} context
 */
public static void printHeaders(Log log, FullHttpResponse msg, ChannelHandlerContext ctx) {
    //the direction is always inbound.
    String logStatement = getDirectionString(true) + "Headers " + resolveContextId(ctx) + " ";
    if (msg.headers() == null || msg.headers().isEmpty()) {
        log.debug(logStatement + "empty");
    } else {
        for (Map.Entry<String, String> entry : msg.headers().entries()) {
            log.debug(logStatement + entry.getKey() + ":" + entry.getValue());
        }
    }
}
 
Example #28
Source File: LogUtils.java    From alfresco-bulk-import with Apache License 2.0 4 votes vote down vote up
public final static boolean info(final Log log)
{
    return(log.isInfoEnabled());
}
 
Example #29
Source File: RangerPerfCollectorTracer.java    From ranger with Apache License 2.0 4 votes vote down vote up
public RangerPerfCollectorTracer(Log logger, String tag, String data) {
	super(logger, tag, data);
	startTimeNanos = System.nanoTime();
}
 
Example #30
Source File: LoggingModule.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
public LoggingModule(Log log){
    this.log=log;
}