View Javadoc

1   package com.atlassian.logging;
2   
3   import com.atlassian.workcontext.api.ImmutableWorkContextReference;
4   import com.atlassian.workcontext.api.WorkContextAvailable;
5   
6   import javax.annotation.Nonnull;
7   import javax.annotation.Nullable;
8   import java.util.Optional;
9   
10  /**
11   * Provides a data exchange point for logging data that is be associated with the WorkContext lifecycle.
12   */
13  public class WorkContextLoggingData {
14  
15      private static ImmutableWorkContextReference<Optional<String>> traceId = new ImmutableWorkContextReference<>();
16      private static ImmutableWorkContextReference<Optional<String>> tenantId = new ImmutableWorkContextReference<>();
17  
18      /**
19       * Returns an Optional that will contain the traceId if it has been set, otherwise it will return {@link Optional#empty}.
20       *
21       * @return An {@link Optional} containing the traceId or {@link Optional#empty}.
22       */
23      @Nonnull
24      public static Optional<String> getTraceId() {
25          if (WorkContextAvailable.isWorkContextAvailableStrict() && traceId.isPresent()) {
26              return traceId.get();
27          }
28          return Optional.empty();
29      }
30  
31      /**
32       * Set the traceId for this WorkContext. Can be null to indicate that there is no traceId available.
33       *
34       * @param traceId The traceId associated with this WorkContext.
35       */
36      public static void setTraceId(@Nullable String traceId) {
37          if (WorkContextAvailable.isWorkContextAvailableStrict()) {
38              WorkContextLoggingData.traceId.initialise(Optional.ofNullable(traceId));
39          }
40      }
41  
42      /**
43       * Returns an {@link String} containing the tenantId. If the tenantId has not been set, then we will return
44       * {@link Optional#empty}.
45       *
46       * @return The actual tenantId or {@link Optional#empty}
47       */
48      @Nonnull
49      public static Optional<String> getTenantId() {
50          if (WorkContextAvailable.isWorkContextAvailableStrict() && tenantId.isPresent()) {
51              return tenantId.get();
52          }
53          // We have not set the tenantId, as opposed to those times where the tenantId is set, but not present.
54          return Optional.empty();
55      }
56  
57      /**
58       * Set the tenantId.
59       *
60       * @param tenantId The tenantId that is associated with this WorkContext. If null is passed, then the WorkContext
61       *                 is considered to be explicitly untenanted.
62       */
63      public static void setTenantId(@Nullable String tenantId) {
64          if (WorkContextAvailable.isWorkContextAvailableStrict()) {
65              WorkContextLoggingData.tenantId.initialise(Optional.ofNullable(tenantId));
66          }
67      }
68  }