下面列出了org.springframework.core.io.DescriptiveResource#org.apache.commons.logging.Log 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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);
}
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);
}
/**
* 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;
}
@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!");
}
}
}
@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;
}
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;
}
}
@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!");
}
}
}
@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;
}
}
}
/**
* 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());
}
}
}
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;
}
/**
* 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);
}
/**
* 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);
}
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);
}
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;
}
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"));
}
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);
}
}
/**
* 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;
}
/**
* 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);
}
}
}
}
}
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);
}
}
@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();
}
/**
* 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++;
}
}
@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());
}
/** @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);
}
}
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);
}
@Test
public void testTrace() {
Log mockLog = mock(Log.class);
InternalLogger logger = new CommonsLogger(mockLog, "foo");
logger.trace("a");
verify(mockLog).trace("a");
}
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);
}
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();
}
public final static void info(final Log log, final String message, final Throwable cause)
{
log.info(PREFIX + message, cause);
}
public static Log getLog(String name){
return getAsyncLogIfNeed(LogFactory.getLog(name));
}
/** @return {@link org.apache.commons.logging.Log} based on the caller's class */
public static Log getLog() {
return getLog(2);
}