下面列出了怎么用org.apache.logging.log4j.ThreadContext的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testLookup() {
final Map<String, String> map = new HashMap<>();
map.put(TESTKEY, TESTVAL);
final StrLookup lookup = new Interpolator(new MapLookup(map));
final StrSubstitutor subst = new StrSubstitutor(lookup);
ThreadContext.put(TESTKEY, TESTVAL);
String value = subst.replace("${TestKey}-${ctx:TestKey}-${sys:TestKey}");
assertEquals("TestValue-TestValue-TestValue", value);
value = subst.replace("${BadKey}");
assertEquals("${BadKey}", value);
value = subst.replace("${BadKey:-Unknown}-${ctx:BadKey:-Unknown}-${sys:BadKey:-Unknown}");
assertEquals("Unknown-Unknown-Unknown", value);
value = subst.replace("${BadKey:-Unknown}-${ctx:BadKey}-${sys:BadKey:-Unknown}");
assertEquals("Unknown-${ctx:BadKey}-Unknown", value);
value = subst.replace("${BadKey:-Unknown}-${ctx:BadKey:-}-${sys:BadKey:-Unknown}");
assertEquals("Unknown--Unknown", value);
}
@Test
public void testConverterFullEmpty() {
ThreadContext.clearMap();
final Message msg = new SimpleMessage("Hello");
final MdcPatternConverter converter = MdcPatternConverter.newInstance(null);
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName("MyLogger") //
.setLevel(Level.DEBUG) //
.setMessage(msg) //
.build();
final StringBuilder sb = new StringBuilder();
converter.format(event, sb);
final String str = sb.toString();
final String expected = "{}";
assertTrue("Incorrect result. Expected " + expected + ", actual " + str, str.equals(expected));
}
@Test
public void gelfLayout() throws IOException {
final Logger logger = context.getLogger();
ThreadContext.put("loginId", "rgoers");
ThreadContext.put("internalId", "12345");
logger.info("My Test Message");
final String gelf = context.getListAppender("list").getMessages().get(0);
final ObjectMapper mapper = new ObjectMapper();
final JsonNode json = mapper.readTree(gelf);
assertEquals("My Test Message", json.get("short_message").asText());
assertEquals("myhost", json.get("host").asText());
assertNotNull(json.get("_loginId"));
assertEquals("rgoers", json.get("_loginId").asText());
assertNull(json.get("_internalId"));
assertNull(json.get("_requestId"));
String message = json.get("full_message").asText();
assertTrue(message.contains("loginId=rgoers"));
assertTrue(message.contains("GelfLayoutTest3"));
}
@Test
public void testThreadContextConfiguration() {
try {
System.setProperty(Constants.LOGBACK_MIDDLEWARE_LOG_DISABLE_PROP_KEY, "true");
SPACES_MAP.remove(new SpaceId(TEST_SPACE));
LoggerSpaceManager.getLoggerBySpace(LogbackIntegrationTest.class.getCanonicalName(),
TEST_SPACE);
ThreadContext.put("testKey", "testValue");
ThreadContext.put("logging.path", "anyPath");
Map<String, Object> properties = new HashMap<String, Object>();
SpringApplication springApplication = new SpringApplication(EmptyConfig.class);
springApplication.setDefaultProperties(properties);
springApplication.run(new String[] {});
Assert.assertTrue("testValue".equals(ThreadContext.get("testKey")));
Assert.assertTrue(Constants.LOGGING_PATH_DEFAULT.equals(ThreadContext
.get("logging.path")));
} finally {
System.getProperties().remove(Constants.LOGBACK_MIDDLEWARE_LOG_DISABLE_PROP_KEY);
}
}
@RequestMapping(value = "/ndc/log4j2", method = RequestMethod.POST)
public ResponseEntity<Investment> postPayment(@RequestBody Investment investment) {
// Add transactionId and owner to NDC
ThreadContext.push("tx.id=" + investment.getTransactionId());
ThreadContext.push("tx.owner=" + investment.getOwner());
try {
log4j2BusinessService.transfer(investment.getAmount());
} finally {
// take out owner from the NDC stack
ThreadContext.pop();
// take out transactionId from the NDC stack
ThreadContext.pop();
ThreadContext.clearAll();
}
return new ResponseEntity<Investment>(investment, HttpStatus.OK);
}
public static void perfTest() throws Exception {
ThreadContext.clearMap();
final Timer complete = new Timer("ThreadContextTest");
complete.start();
ThreadContext.put("Var1", "value 1");
ThreadContext.put("Var2", "value 2");
ThreadContext.put("Var3", "value 3");
ThreadContext.put("Var4", "value 4");
ThreadContext.put("Var5", "value 5");
ThreadContext.put("Var6", "value 6");
ThreadContext.put("Var7", "value 7");
ThreadContext.put("Var8", "value 8");
ThreadContext.put("Var9", "value 9");
ThreadContext.put("Var10", "value 10");
final int loopCount = 1000000;
final Timer timer = new Timer("ThreadContextCopy", loopCount);
timer.start();
for (int i = 0; i < loopCount; ++i) {
final Map<String, String> map = ThreadContext.getImmutableContext();
assertNotNull(map);
}
timer.stop();
complete.stop();
System.out.println(timer.toString());
System.out.println(complete.toString());
}
private void initTranslator(final RingBufferLogEventTranslator translator, final String fqcn,
final StackTraceElement location, final Level level, final Marker marker,
final Message message, final Throwable thrown) {
translator.setBasicValues(this, name, marker, fqcn, level, message, //
// don't construct ThrowableProxy until required
thrown,
// needs shallow copy to be fast (LOG4J2-154)
ThreadContext.getImmutableStack(), //
location,
CLOCK, //
nanoClock //
);
}
private void handle(CephToCephMigrateVolumeSegmentMsg msg) {
final CephToCephMigrateVolumeSegmentCmd cmd = new CephToCephMigrateVolumeSegmentCmd();
cmd.setParentUuid(msg.getParentUuid());
cmd.setResourceUuid(msg.getResourceUuid());
cmd.setSrcInstallPath(msg.getSrcInstallPath());
cmd.setDstInstallPath(msg.getDstInstallPath());
cmd.setDstMonHostname(msg.getDstMonHostname());
cmd.setDstMonSshUsername(msg.getDstMonSshUsername());
cmd.setDstMonSshPassword(msg.getDstMonSshPassword());
cmd.setDstMonSshPort(msg.getDstMonSshPort());
final String apiId = ThreadContext.get(Constants.THREAD_CONTEXT_API);
final CephToCephMigrateVolumeSegmentReply reply = new CephToCephMigrateVolumeSegmentReply();
new HttpCaller<>(CEPH_TO_CEPH_MIGRATE_VOLUME_SEGMENT_PATH, cmd, StorageMigrationRsp.class, new ReturnValueCompletion<StorageMigrationRsp>(msg) {
@Override
public void success(StorageMigrationRsp returnValue) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
}, TimeUnit.MILLISECONDS, msg.getTimeout()).specifyOrder(apiId).call();
}
@Override
public void start(LongJobVO job, ReturnValueCompletion<APIEvent> completion) {
RevertVolumeSnapshotMsg msg = new RevertVolumeSnapshotMsg();
APIRevertVolumeFromSnapshotMsg apiMessage = JSONObjectUtil.toObject(job.getJobData(), APIRevertVolumeFromSnapshotMsg.class);
msg.setSnapshotUuid(apiMessage.getSnapshotUuid());
msg.setVolumeUuid(apiMessage.getVolumeUuid());
msg.setTreeUuid(apiMessage.getTreeUuid());
msg.setSession(apiMessage.getSession());
bus.makeServiceIdByManagementNodeId(msg, VolumeSnapshotConstant.SERVICE_ID, getRoutedMnId(apiMessage));
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
auditResourceUuid = msg.getVolumeUuid();
if (reply.isSuccess()) {
APIRevertVolumeFromSnapshotEvent evt = new APIRevertVolumeFromSnapshotEvent(ThreadContext.get(Constants.THREAD_CONTEXT_API));
completion.success(evt);
} else {
completion.fail(reply.getError());
}
}
});
}
@Override
public void sessionEvent(MCRSessionEvent event) {
switch (event.getType()) {
case activated:
ThreadContext.put("ipAddress", event.getSession().getCurrentIP());
ThreadContext.put("loginId", event.getSession().getUserInformation().getUserID());
ThreadContext.put("mcrSession", event.getSession().getID());
ThreadContext.put("language", event.getSession().getCurrentLanguage());
break;
case passivated:
ThreadContext.clearMap();
break;
default:
break;
}
}
@Override
public void submitLongJob(SubmitLongJobMsg msg, CloudBusCallBack submitCallBack, Consumer<APIEvent> jobCallBack) {
String apiId = ThreadContext.get(Constants.THREAD_CONTEXT_API);
longJobCallBacks.put(apiId, jobCallBack);
bus.makeLocalServiceId(msg, LongJobConstants.SERVICE_ID);
bus.send(msg, new CloudBusCallBack(submitCallBack) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
longJobCallBacks.remove(apiId);
}
if (submitCallBack != null) {
submitCallBack.run(reply);
}
}
});
}
@Test
public void testValidationFailureForMissingRequestContextAttribute() {
MutableBoolean exceptionHandled = new MutableBoolean(false);
LogEventFactory.setDefaultHandler((message, ex) -> {
assertThat(ex, instanceOf(ConstraintValidationException.class));
exceptionHandled.setTrue();
});
Transfer transfer = LogEventFactory.getEvent(Transfer.class);
ThreadContext.put("companyId", "12345");
ThreadContext.put("ipAddress", "127.0.0.1");
ThreadContext.put("environment", "dev");
ThreadContext.put("product", "TestProduct");
ThreadContext.put("timeZone", "America/Phoenix");
ThreadContext.put("loginId", "TestUser");
transfer.setToAccount(123456);
transfer.setFromAccount(111111);
transfer.setAmount(new BigDecimal(111.55));
transfer.logEvent();
assertTrue("Should have thrown a ConstraintValidationException", exceptionHandled.isTrue());
}
@Test
public void testValidationFailureForMissingEventAttribute() {
MutableBoolean exceptionHandled = new MutableBoolean(false);
LogEventFactory.setDefaultHandler((message, ex) -> {
assertThat(ex, instanceOf(ConstraintValidationException.class));
exceptionHandled.setTrue();
});
Transfer transfer = LogEventFactory.getEvent(Transfer.class);
ThreadContext.put("accountNumber", "12345");
ThreadContext.put("companyId", "12345");
ThreadContext.put("userId", "JohnDoe");
ThreadContext.put("ipAddress", "127.0.0.1");
ThreadContext.put("environment", "dev");
ThreadContext.put("product", "TestProduct");
ThreadContext.put("timeZone", "America/Phoenix");
ThreadContext.put("loginId", "TestUser");
transfer.setToAccount(123456);
transfer.setFromAccount(111111);
transfer.logEvent();
assertTrue("Should have thrown a ConstraintValidationException", exceptionHandled.isTrue());
}
@Override
public ThreadContext.ContextStack convertToEntityAttribute(final String s) {
if (Strings.isEmpty(s)) {
return null;
}
List<String> list;
try {
list = ContextMapJsonAttributeConverter.OBJECT_MAPPER.readValue(s, new TypeReference<List<String>>() { });
} catch (final IOException e) {
throw new PersistenceException("Failed to convert JSON string to list for stack.", e);
}
final DefaultThreadContextStack result = new DefaultThreadContextStack(true);
result.addAll(list);
return result;
}
public static void main(String... args) throws Exception {
ThreadContext.put("console-level", "");
ThreadContext.put("file-level", "");
CommandLine cmd = new CommandLine(new DataDefender())
.registerConverter(Requirement.class, new RequirementConverter())
.setParameterExceptionHandler(new ShortErrorMessageHandler());
int exitCode = cmd.execute(args);
System.exit(exitCode);
}
static Map<String, String> createMap(final List<Property> properties) {
final Map<String, String> contextMap = ThreadContext.getImmutableContext();
if (properties == null || properties.isEmpty()) {
return contextMap; // may be ThreadContext.EMPTY_MAP but not null
}
final Map<String, String> map = new HashMap<>(contextMap);
for (final Property prop : properties) {
if (!map.containsKey(prop.getName())) {
map.put(prop.getName(), prop.getValue());
}
}
return Collections.unmodifiableMap(map);
}
@Override
public void start(LongJobVO job, ReturnValueCompletion<APIEvent> completion) {
CreateDataVolumeTemplateFromVolumeMsg msg = JSONObjectUtil.toObject(job.getJobData(), CreateDataVolumeTemplateFromVolumeMsg.class);
if (msg.getResourceUuid() == null) {
msg.setResourceUuid(Platform.getUuid());
job.setJobData(JSONObjectUtil.toJsonString(msg));
dbf.updateAndRefresh(job);
}
bus.makeLocalServiceId(msg, ImageConstant.SERVICE_ID);
bus.send(msg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
CreateDataVolumeTemplateFromVolumeReply r = reply.castReply();
APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(ThreadContext.get(Constants.THREAD_CONTEXT_API));
auditResourceUuid = r.getInventory().getUuid();
evt.setInventory(r.getInventory());
if (jobCanceled(job.getUuid())) {
deleteAfterCancel(r.getInventory(), job, completion);
} else {
completion.success(evt);
}
} else {
auditResourceUuid = msg.getResourceUuid();
completion.fail(reply.getError());
}
}
});
}
/**
* 将上下文环境变量信息加入到ThreadContext中,以便打印到日志
*/
public static void addContext2ThreadContext() {
ServiceContext context = ServiceContext.getContext();
if (context == null) {
log.warn("上下文未处理化,context is null");
return;
}
ThreadContext.put(ContextConstKey.REQUEST_NO, StringUtils.isEmpty(context.getRequestNo()) ? "" : context.getRequestNo());
ThreadContext.put(ContextConstKey.SYS_CODE, StringUtils.isEmpty(context.getSysCode()) ? "" : context.getSysCode());
ThreadContext.put(ContextConstKey.LOCAL_IP, NetUtils.getLocalIP());
ThreadContext.put(ContextConstKey.BEAN_NAME, StringUtils.isEmpty(context.getBeanName()) ? "" : context.getBeanName());
}
@Test
public void test3() {
ThreadContext.push("foo");
ThreadContext.push("bar");
ThreadContext.push("baz");
testConverter("foo bar baz");
}
private void testContextDataInjector() {
ReadOnlyThreadContextMap readOnlythreadContextMap = getThreadContextMap();
assertThat("thread context map class name",
(readOnlythreadContextMap == null) ? null : readOnlythreadContextMap.getClass().getName(),
is(equalTo(readOnlythreadContextMapClassName)));
ContextDataInjector contextDataInjector = createInjector();
StringMap stringMap = contextDataInjector.injectContextData(null, new SortedArrayStringMap());
assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
if (!stringMap.isFrozen()) {
stringMap.clear();
assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
}
ThreadContext.put("foo", "bum");
ThreadContext.put("baz", "bam");
assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bum"), hasEntry("baz", "bam")));
if (stringMap.isFrozen()) {
assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
} else {
assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
}
}
public static String getRequestId() {
String uuidStr = ThreadContext.get(REQUEST_ID);
if (uuidStr == null) {
ThreadContext.put(REQUEST_ID, UuidUtil.getTimeBasedUuid().toString());
uuidStr = ThreadContext.get(REQUEST_ID);
}
return uuidStr;
}
@Override
public ReadOnlyStringMap rawContextData() {
final ReadOnlyThreadContextMap map = ThreadContext.getThreadContextMap();
if (map instanceof ReadOnlyStringMap) {
return (ReadOnlyStringMap) map;
}
// note: default ThreadContextMap is null
final Map<String, String> copy = ThreadContext.getImmutableContext();
return copy.isEmpty() ? ContextDataFactory.emptyFrozenContextData() : new JdkMapAdapterStringMap(copy);
}
@BeforeClass
public static void setupClass() {
ThreadContext.clearAll();
ConfigurationFactory.setConfigurationFactory(cf);
final LoggerContext ctx = LoggerContext.getContext();
ctx.reconfigure();
}
private Runnable newTriggerTask() {
return new Runnable() {
@Override
public void run() {
// initialize the thread context
ThreadContext.put("function", WindowUtils.getFullyQualifiedName(
context.getTenant(), context.getNamespace(), context.getFunctionName()));
// do not process current timestamp since tuples might arrive while the trigger is executing
long now = System.currentTimeMillis() - 1;
try {
/*
* set the current timestamp as the reference time for the eviction policy
* to evict the events
*/
evictionPolicy.setContext(new DefaultEvictionContext(now, null, null, duration));
handler.onTrigger();
} catch (Throwable th) {
log.error("handler.onTrigger failed ", th);
/*
* propagate it so that task gets canceled and the exception
* can be retrieved from executorFuture.get()
*/
throw th;
}
}
};
}
@Override
public Long getApiTimeout() {
String type = ThreadContext.get(Constants.THREAD_CONTEXT_TASK_NAME);
if (type != null && longJobClasses.contains(type)) {
Class<? extends APIMessage> batchJobFor = useApiTimeout.get(type);
if (batchJobFor != null) {
return getMessageTimeout(batchJobFor);
}
// default input unit is second should be changed to millis
return TimeUnit.SECONDS.toMillis(LongJobGlobalConfig.LONG_JOB_DEFAULT_TIMEOUT.value(Long.class));
}
return null;
}
@Test
public void interceptorTest2() {
TraceContext traceContext = spy(TraceContext.class);
Trace trace = mock(Trace.class);
TraceId traceId = spy(TraceId.class);
when(traceContext.currentTraceObject()).thenReturn(trace);
when(traceContext.currentRawTraceObject()).thenReturn(trace);
when(traceContext.currentRawTraceObject().getTraceId()).thenReturn(traceId);
when(traceContext.currentRawTraceObject().getTraceId().getTransactionId()).thenReturn("aaa");
when(traceContext.currentRawTraceObject().getTraceId().getSpanId()).thenReturn(112343l);
LogEventFactoryInterceptor interceptor = spy(new LogEventFactoryInterceptor(traceContext));
interceptor.before(null);
interceptor.after(null, null, null);
Assert.assertTrue(ThreadContext.get(TRANSACTION_ID) != null);
}
@Before
public void setupAWSXRay() {
Emitter blankEmitter = Mockito.mock(Emitter.class);
Mockito.doReturn(true).when(blankEmitter).sendSegment(Mockito.any());
Mockito.doReturn(true).when(blankEmitter).sendSubsegment(Mockito.any());
Log4JSegmentListener segmentListener = new Log4JSegmentListener();
AWSXRay.setGlobalRecorder(AWSXRayRecorderBuilder.standard()
.withEmitter(blankEmitter)
.withSegmentListener(segmentListener)
.build());
AWSXRay.clearTraceEntity();
ThreadContext.clearAll();
}
@Test
public void testSetPrefix() {
Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
listener.setPrefix("");
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID);
listener.onSetEntity(null, seg);
Assert.assertEquals(TRACE_ID.toString() + "@" + seg.getId(), ThreadContext.get(TRACE_ID_KEY));
}
@Test
public void testUnsampledSegmentInjection() {
Log4JSegmentListener listener = (Log4JSegmentListener) AWSXRay.getGlobalRecorder().getSegmentListeners().get(0);
listener.setPrefix("");
Segment seg = new SegmentImpl(AWSXRay.getGlobalRecorder(), "test", TRACE_ID);
seg.setSampled(false);
listener.onSetEntity(null, seg);
Assert.assertNull(ThreadContext.get(TRACE_ID_KEY));
}
private LongJobVO createSuccessLongJob(APISubmitLongJobMsg msg) {
// create LongJobVO
LongJobVO vo = new LongJobVO();
if (msg.getResourceUuid() != null) {
vo.setUuid(msg.getResourceUuid());
} else {
vo.setUuid(Platform.getUuid());
}
if (msg.getName() != null) {
vo.setName(msg.getName());
} else {
vo.setName(msg.getJobName());
}
vo.setDescription(msg.getDescription());
vo.setApiId(ThreadContext.getImmutableContext().get(Constants.THREAD_CONTEXT_API));
vo.setJobName(msg.getJobName());
vo.setJobData(msg.getJobData());
vo.setState(LongJobState.Succeeded);
vo.setJobResult(LongJobUtils.succeeded);
vo.setTargetResourceUuid(msg.getTargetResourceUuid());
vo.setManagementNodeUuid(Platform.getManagementServerId());
vo.setAccountUuid(msg.getSession().getAccountUuid());
vo = dbf.persistAndRefresh(vo);
msg.setJobUuid(vo.getUuid());
tagMgr.createTags(msg.getSystemTags(), msg.getUserTags(), vo.getUuid(), LongJobVO.class.getSimpleName());
return vo;
}