Java Code Examples for org.apache.logging.log4j.Logger#trace()
The following examples show how to use
org.apache.logging.log4j.Logger#trace() .
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: ConsoleAppenderAnsiStyleLayoutMain.java From logging-log4j2 with Apache License 2.0 | 7 votes |
public void test(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml" : args[0]; try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class); logger.fatal("Fatal message."); logger.error("Error message."); logger.warn("Warning message."); logger.info("Information message."); logger.debug("Debug message."); logger.trace("Trace message."); logger.error("Error message.", new IOException("test")); } }
Example 2
Source File: ForwardLogHandler.java From Kettle with GNU General Public License v3.0 | 6 votes |
@Override public void publish(LogRecord record) { Logger logger = getLogger(String.valueOf(record.getLoggerName())); // See SPIGOT-1230 Throwable exception = record.getThrown(); Level level = record.getLevel(); String message = getFormatter().formatMessage(record); if (level == Level.SEVERE) { logger.error(message, exception); } else if (level == Level.WARNING) { logger.warn(message, exception); } else if (level == Level.INFO) { logger.info(message, exception); } else if (level == Level.CONFIG) { logger.debug(message, exception); } else { logger.trace(message, exception); } }
Example 3
Source File: Log4j2MetricsTest.java From micrometer with Apache License 2.0 | 6 votes |
@Test void log4j2LevelMetrics() { new Log4j2Metrics().bindTo(registry); assertThat(registry.get("log4j2.events").counter().count()).isEqualTo(0.0); Logger logger = LogManager.getLogger(Log4j2MetricsTest.class); Configurator.setLevel(Log4j2MetricsTest.class.getName(), Level.INFO); logger.info("info"); logger.warn("warn"); logger.fatal("fatal"); logger.error("error"); logger.debug("debug"); // shouldn't record a metric as per log level config logger.trace("trace"); // shouldn't record a metric as per log level config assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1.0); assertThat(registry.get("log4j2.events").tags("level", "warn").counter().count()).isEqualTo(1.0); assertThat(registry.get("log4j2.events").tags("level", "fatal").counter().count()).isEqualTo(1.0); assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(1.0); assertThat(registry.get("log4j2.events").tags("level", "debug").counter().count()).isEqualTo(0.0); assertThat(registry.get("log4j2.events").tags("level", "trace").counter().count()).isEqualTo(0.0); }
Example 4
Source File: test.java From vscode-extension with MIT License | 6 votes |
private static LocalCheckpointTracker createLocalCheckpointTracker(EngineConfig engineConfig, SegmentInfos lastCommittedSegmentInfos, Logger logger, Supplier<Searcher> searcherSupplier, BiFunction<Long, Long, LocalCheckpointTracker> localCheckpointTrackerSupplier) { try { final SequenceNumbers.CommitInfo seqNoStats = SequenceNumbers.loadSeqNoInfoFromLuceneCommit(lastCommittedSegmentInfos.userData.entrySet()); final long maxSeqNo = seqNoStats.maxSeqNo; final long localCheckpoint = seqNoStats.localCheckpoint; logger.trace("recovered maximum sequence number [{}] and local checkpoint [{}]", maxSeqNo, localCheckpoint); final LocalCheckpointTracker tracker = localCheckpointTrackerSupplier.apply(maxSeqNo, localCheckpoint); // Operations that are optimized using max_seq_no_of_updates optimization must not be processed twice; otherwise, they will // create duplicates in Lucene. To avoid this we check the LocalCheckpointTracker to see if an operation was already processed. // Thus, we need to restore the LocalCheckpointTracker bit by bit to ensure the consistency between LocalCheckpointTracker and // Lucene index. This is not the only solution since we can bootstrap max_seq_no_of_updates with max_seq_no of the commit to // disable the MSU optimization during recovery. Here we prefer to maintain the consistency of LocalCheckpointTracker. if (localCheckpoint < maxSeqNo && engineConfig.getIndexSettings().isSoftDeleteEnabled()) { try (Searcher searcher = searcherSupplier.get()) { Lucene.scanSeqNosInReader(searcher.getDirectoryReader(), localCheckpoint + 1, maxSeqNo, tracker::markSeqNoAsCompleted); } } return tracker; } catch (IOException ex) { throw new EngineCreationFailureException(engineConfig.getShardId(), "failed to create local checkpoint tracker", ex); } }
Example 5
Source File: Scope.java From meghanada-server with GNU General Public License v3.0 | 6 votes |
public void dumpFieldAccess(final Logger logger) { for (final FieldAccess fa : this.fieldAccesses) { if (fa.returnType == null) { logger.warn("missing returnType {}", fa); } else { logger.trace("# {}", fa); } } for (final MethodCall mc : this.methodCalls) { if (mc.returnType == null) { logger.warn("missing returnType {}", mc); } else { logger.trace("# {}", mc); } } }
Example 6
Source File: ForwardLogHandler.java From Thermos with GNU General Public License v3.0 | 6 votes |
@Override public void publish(LogRecord record) { Logger logger = getLogger(record.getLoggerName()); Throwable exception = record.getThrown(); Level level = record.getLevel(); String message = getFormatter().formatMessage(record); if (level == Level.SEVERE) { logger.error(message, exception); } else if (level == Level.WARNING) { logger.warn(message, exception); } else if (level == Level.INFO) { logger.info(message, exception); } else if (level == Level.CONFIG) { logger.debug(message, exception); } else { logger.trace(message, exception); } }
Example 7
Source File: ChildMemoryCircuitBreaker.java From crate with Apache License 2.0 | 6 votes |
/** * Create a circuit breaker that will break if the number of estimated * bytes grows above the limit. All estimations will be multiplied by * the given overheadConstant. Uses the given oldBreaker to initialize * the starting offset. * @param settings settings to configure this breaker * @param parent parent circuit breaker service to delegate tripped breakers to * @param name the name of the breaker * @param oldBreaker the previous circuit breaker to inherit the used value from (starting offset) */ public ChildMemoryCircuitBreaker(BreakerSettings settings, ChildMemoryCircuitBreaker oldBreaker, Logger logger, CircuitBreakerService parent, String name) { this.name = name; this.settings = settings; this.memoryBytesLimit = settings.getLimit(); this.overheadConstant = settings.getOverhead(); if (oldBreaker == null) { this.used = new AtomicLong(0); this.trippedCount = new AtomicLong(0); } else { this.used = oldBreaker.used; this.trippedCount = oldBreaker.trippedCount; } this.logger = logger; if (logger.isTraceEnabled()) { logger.trace("creating ChildCircuitBreaker with settings {}", this.settings); } this.parent = parent; }
Example 8
Source File: JdbcAppenderColumnMappingLiteralTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { try (Connection connection = jdbcRule.getConnection()) { final Error exception = new Error("This is a test."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (final PrintWriter writer = new PrintWriter(outputStream)) { exception.printStackTrace(writer); } final String stackTrace = outputStream.toString(); final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig"); logger.trace("Data source logged message 01."); logger.fatal("Error from data source 02.", exception); Thread.sleep(1000); try (final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT * FROM dsMappingLogEntry ORDER BY id")) { assertTrue("There should be at least one row.", resultSet.next()); assertEquals("The level column is not correct (1).", "FATAL", resultSet.getNString("level")); assertEquals("The logger column is not correct (1).", logger.getName(), resultSet.getNString("logger")); assertEquals("The message column is not correct (1).", "Hello World!", resultSet.getString("message")); assertEquals("The exception column is not correct (1).", stackTrace, IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1)); assertFalse("There should not be two rows.", resultSet.next()); } } }
Example 9
Source File: JdbcAppenderColumnMappingPatternTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { try (Connection connection = jdbcRule.getConnection()) { final Error exception = new Error("This is a test."); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (final PrintWriter writer = new PrintWriter(outputStream)) { exception.printStackTrace(writer); } final String stackTrace = outputStream.toString(); final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig"); logger.trace("Data source logged message 01."); logger.fatal("Error from data source 02.", exception); Thread.sleep(1000); try (final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT * FROM dsMappingLogEntry ORDER BY id")) { assertTrue("There should be at least one row.", resultSet.next()); assertEquals("The level column is not correct (1).", "FATAL", resultSet.getNString("level")); assertEquals("The logger column is not correct (1).", logger.getName(), resultSet.getNString("logger")); assertEquals("The message column is not correct (1).", "Error from data source 02.", resultSet.getString("message")); assertEquals("The exception column is not correct (1).", stackTrace, IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1)); assertFalse("There should not be two rows.", resultSet.next()); } } }
Example 10
Source File: InternalClusterInfoService.java From crate with Apache License 2.0 | 5 votes |
static void buildShardLevelInfo(Logger logger, ShardStats[] stats, ImmutableOpenMap.Builder<String, Long> newShardSizes, ImmutableOpenMap.Builder<ShardRouting, String> newShardRoutingToDataPath, ClusterState state) { for (ShardStats s : stats) { newShardRoutingToDataPath.put(s.getShardRouting(), s.getDataPath()); long size = s.getStats().getStore().sizeInBytes(); String sid = ClusterInfo.shardIdentifierFromRouting(s.getShardRouting()); if (logger.isTraceEnabled()) { logger.trace("shard: {} size: {}", sid, size); } newShardSizes.put(sid, size); } }
Example 11
Source File: AbstractJdbcAppenderDataSourceTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test public void testDataSourceConfig() throws Exception { try (final Connection connection = jdbcRule.getConnectionSource().getConnection()) { final Error exception = new Error("Final error massage is fatal!"); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (final PrintWriter writer = new PrintWriter(outputStream)) { exception.printStackTrace(writer); } final String stackTrace = outputStream.toString(); final long millis = System.currentTimeMillis(); final Logger logger = LogManager.getLogger(this.getClass().getName() + ".testDataSourceConfig"); logger.trace("Data source logged message 01."); logger.fatal("Error from data source 02.", exception); try (final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery("SELECT * FROM dsLogEntry ORDER BY id")) { assertTrue("There should be at least one row.", resultSet.next()); final long date = resultSet.getTimestamp("eventDate").getTime(); assertTrue("The date should be later than pre-logging (1).", date >= millis); assertTrue("The date should be earlier than now (1).", date <= System.currentTimeMillis()); assertEquals("The literal column is not correct (1).", "Literal Value of Data Source", resultSet.getString("literalColumn")); assertEquals("The level column is not correct (1).", "FATAL", resultSet.getNString("level")); assertEquals("The logger column is not correct (1).", logger.getName(), resultSet.getNString("logger")); assertEquals("The message column is not correct (1).", "Error from data source 02.", resultSet.getString("message")); assertEquals("The exception column is not correct (1).", stackTrace, IOUtils.readStringAndClose(resultSet.getNClob("exception").getCharacterStream(), -1)); assertFalse("There should not be two rows.", resultSet.next()); } } }
Example 12
Source File: Store.java From crate with Apache License 2.0 | 5 votes |
/** * Tries to open an index for the given location. This includes reading the * segment infos and possible corruption markers. If the index can not * be opened, an exception is thrown */ public static void tryOpenIndex(Path indexLocation, ShardId shardId, NodeEnvironment.ShardLocker shardLocker, Logger logger) throws IOException, ShardLockObtainFailedException { try (ShardLock lock = shardLocker.lock(shardId, "open index", TimeUnit.SECONDS.toMillis(5)); Directory dir = new SimpleFSDirectory(indexLocation)) { failIfCorrupted(dir, shardId); SegmentInfos segInfo = Lucene.readSegmentInfos(dir); logger.trace("{} loaded segment info [{}]", shardId, segInfo); } }
Example 13
Source File: Store.java From crate with Apache License 2.0 | 5 votes |
/** * Returns <code>true</code> iff the given location contains an index an the index * can be successfully opened. This includes reading the segment infos and possible * corruption markers. */ public static boolean canOpenIndex(Logger logger, Path indexLocation, ShardId shardId, NodeEnvironment.ShardLocker shardLocker) throws IOException { try { tryOpenIndex(indexLocation, shardId, shardLocker, logger); } catch (Exception ex) { logger.trace(() -> new ParameterizedMessage("Can't open index for path [{}]", indexLocation), ex); return false; } return true; }
Example 14
Source File: MergePolicyConfig.java From crate with Apache License 2.0 | 5 votes |
MergePolicyConfig(Logger logger, IndexSettings indexSettings) { this.logger = logger; final double forceMergeDeletesPctAllowed = indexSettings.getValue(INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED_SETTING); // percentage final ByteSizeValue floorSegment = indexSettings.getValue(INDEX_MERGE_POLICY_FLOOR_SEGMENT_SETTING); int maxMergeAtOnce = indexSettings.getValue(INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_SETTING); final int maxMergeAtOnceExplicit = indexSettings.getValue(INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT_SETTING); // TODO is this really a good default number for max_merge_segment, what happens for large indices, won't they end up with many segments? final ByteSizeValue maxMergedSegment = indexSettings.getValue(INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT_SETTING); double segmentsPerTier = indexSettings.getValue(INDEX_MERGE_POLICY_SEGMENTS_PER_TIER_SETTING); double reclaimDeletesWeight = indexSettings.getValue(INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT_SETTING); final double deletesPctAllowed = indexSettings.getValue(INDEX_MERGE_POLICY_DELETES_PCT_ALLOWED_SETTING); this.mergesEnabled = indexSettings.getSettings().getAsBoolean(INDEX_MERGE_ENABLED, true); if (mergesEnabled == false) { logger.warn("[{}] is set to false, this should only be used in tests and can cause serious problems in production environments", INDEX_MERGE_ENABLED); } maxMergeAtOnce = adjustMaxMergeAtOnceIfNeeded(maxMergeAtOnce, segmentsPerTier); mergePolicy.setNoCFSRatio(indexSettings.getValue(INDEX_COMPOUND_FORMAT_SETTING)); mergePolicy.setForceMergeDeletesPctAllowed(forceMergeDeletesPctAllowed); mergePolicy.setFloorSegmentMB(floorSegment.getMbFrac()); mergePolicy.setMaxMergeAtOnce(maxMergeAtOnce); mergePolicy.setMaxMergeAtOnceExplicit(maxMergeAtOnceExplicit); mergePolicy.setMaxMergedSegmentMB(maxMergedSegment.getMbFrac()); mergePolicy.setSegmentsPerTier(segmentsPerTier); mergePolicy.setDeletesPctAllowed(deletesPctAllowed); if (logger.isTraceEnabled()) { logger.trace("using [tiered] merge mergePolicy with expunge_deletes_allowed[{}], floor_segment[{}], max_merge_at_once[{}], max_merge_at_once_explicit[{}], max_merged_segment[{}], segments_per_tier[{}], deletes_pct_allowed[{}]", forceMergeDeletesPctAllowed, floorSegment, maxMergeAtOnce, maxMergeAtOnceExplicit, maxMergedSegment, segmentsPerTier, deletesPctAllowed); } }
Example 15
Source File: CustomLoggingIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenLoggerWithFailoverConfig_whenLog_thanOK() throws Exception { Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER"); Exception e = new RuntimeException("This is only a test!"); logger.trace("This is a syslog message at TRACE level."); logger.debug("This is a syslog message at DEBUG level."); logger.info("This is a syslog message at INFO level. This is the minimum visible level."); logger.warn("This is a syslog message at WARN level."); logger.error("This is a syslog message at ERROR level.", e); logger.fatal("This is a syslog message at FATAL level."); }
Example 16
Source File: CustomLoggingIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenLoggerWithConsoleConfig_whenFilterByMarker_thanOK() throws Exception { Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); Marker appError = MarkerManager.getMarker("APP_ERROR"); Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); logger.error(appError, "This marker message at ERROR level should be hidden."); logger.trace(connectionTrace, "This is a marker message at TRACE level."); }
Example 17
Source File: CustomLoggingIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void givenLoggerWithConsoleConfig_whenLogToConsoleInColors_thanOK() throws Exception { Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); Exception e = new RuntimeException("This is only a test!"); logger.trace("This is a colored message at TRACE level."); logger.debug("This is a colored message at DEBUG level. " + "This is the minimum visible level."); logger.info("This is a colored message at INFO level."); logger.warn("This is a colored message at WARN level."); logger.error("This is a colored message at ERROR level.", e); logger.fatal("This is a colored message at FATAL level."); }
Example 18
Source File: Scope.java From meghanada-server with GNU General Public License v3.0 | 5 votes |
public void dumpVariable(final Logger logger) { for (final Variable v : this.variables) { if (!v.name.equals("NULL_LITERAL") && isNull(v.fqcn)) { logger.warn("missing fqcn {}", v); } else { logger.trace("# {}", v); } } }
Example 19
Source File: RootTask.java From crate with Apache License 2.0 | 4 votes |
private RootTask(Logger logger, UUID jobId, String coordinatorNodeId, Collection<String> participatingNodes, JobsLogs jobsLogs, List<Task> orderedTasks, @Nullable ProfilingContext profilingContext) throws Exception { this.logger = logger; this.coordinatorNodeId = coordinatorNodeId; this.participatedNodes = participatingNodes; this.jobId = jobId; this.jobsLogs = jobsLogs; int numTasks = orderedTasks.size(); if (profilingContext == null) { taskTimersByPhaseId = null; profilingFuture = null; profiler = null; } else { profiler = profilingContext; taskTimersByPhaseId = new ConcurrentHashMap<>(numTasks); profilingFuture = new CompletableFuture<>(); } orderedTaskIds = new IntArrayList(numTasks); tasksByPhaseId = new ConcurrentHashMap<>(numTasks); this.numTasks = new AtomicInteger(numTasks); traceEnabled = logger.isTraceEnabled(); for (Task task : orderedTasks) { int phaseId = task.id(); orderedTaskIds.add(phaseId); if (tasksByPhaseId.put(phaseId, task) != null) { throw new IllegalArgumentException("Task for " + phaseId + " already added"); } task.completionFuture().whenComplete(new RemoveTaskListener(phaseId)); jobsLogs.operationStarted(phaseId, jobId, task.name(), task::bytesUsed); task.prepare(); if (profiler != null) { String subContextName = ProfilingContext.generateProfilingKey(task.id(), task.name()); if (taskTimersByPhaseId.put(phaseId, profiler.createTimer(subContextName)) != null) { throw new IllegalArgumentException("Timer for " + phaseId + " already added"); } } if (traceEnabled) { logger.trace("adding subContext {}, now there are {} tasksByPhaseId", phaseId, tasksByPhaseId.size()); } } }
Example 20
Source File: AzureConfiguration.java From crate with Apache License 2.0 | 4 votes |
/** * Check if discovery is meant to start * * @param settings settings to extract cloud enabled parameter from * @return true if we can start discovery features */ public static boolean isDiscoveryReady(Settings settings, Logger logger) { // Cloud services are disabled if (!isCloudReady(settings)) { logger.trace("cloud settings are disabled"); return false; } // User set discovery.zen.hosts_provider: azure if (!AZURE.equalsIgnoreCase(settings.get(DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING.getKey()))) { logger.trace("{} not set to {}", DiscoveryModule.DISCOVERY_SEED_PROVIDERS_SETTING.getKey(), AZURE); return false; } if (isPropertyMissing(settings, Management.SUBSCRIPTION_ID.getKey()) || isPropertyMissing(settings, Management.RESOURCE_GROUP_NAME.getKey()) || isPropertyMissing(settings, Management.TENANT_ID.getKey()) || isPropertyMissing(settings, Management.APP_ID.getKey()) || isPropertyMissing(settings, Management.APP_SECRET.getKey()) ) { logger.warn("one or more azure discovery settings are missing. " + "Check crate.yml file. Should have [{}], [{}], [{}] and [{}].", Management.SUBSCRIPTION_ID, Management.RESOURCE_GROUP_NAME, Management.TENANT_ID, Management.APP_ID, Management.APP_SECRET); return false; } String discoveryType = AzureComputeService.Discovery.DISCOVERY_METHOD.get(settings); if (!(SUBNET.equalsIgnoreCase(discoveryType) || VNET.equalsIgnoreCase(discoveryType) || discoveryType == null)) { logger.warn("{} must be set to {} or {}. Ignoring value {}", AzureComputeService.Discovery.DISCOVERY_METHOD.getKey(), VNET, SUBNET, discoveryType); } logger.trace("all required properties for azure discovery are set!"); return true; }