|
16 | 16 |
|
17 | 17 | package com.google.cloud.logging;
|
18 | 18 |
|
| 19 | +import static com.google.common.base.Preconditions.checkElementIndex; |
| 20 | + |
19 | 21 | import com.google.common.base.MoreObjects;
|
20 | 22 | import com.google.logging.v2.LogEntrySourceLocation;
|
21 | 23 | import java.io.Serializable;
|
@@ -154,4 +156,30 @@ static SourceLocation fromPb(LogEntrySourceLocation sourceLocationPb) {
|
154 | 156 | .setFunction(sourceLocationPb.getFunction())
|
155 | 157 | .build();
|
156 | 158 | }
|
| 159 | + |
| 160 | + /** |
| 161 | + * Creates instance of {@link SourceLocation} based on stack trace information. Caller should |
| 162 | + * provide the level in the stack where the information can be located. The stack trace level |
| 163 | + * should be {@code 0} to display information for the caller of the method. |
| 164 | + * |
| 165 | + * @param level Zero-based non-negative integer defining the level in the stack trace where {@code |
| 166 | + * 0} is topmost element. |
| 167 | + * @return a new instance of {@link SourceLocation} populated with file name, method and line |
| 168 | + * number information. |
| 169 | + * @throws IndexOutOfBoundsException if the provided {@link level} is negative or greater than the |
| 170 | + * current call stack. |
| 171 | + */ |
| 172 | + static SourceLocation fromCurrentContext(int level) { |
| 173 | + StackTraceElement[] stackTrace = (new Exception()).getStackTrace(); |
| 174 | + Builder builder = newBuilder(); |
| 175 | + // need to take info from 1 level down the stack to compensate the call to this |
| 176 | + // method |
| 177 | + int indexPlus = checkElementIndex(level, stackTrace.length - 1) + 1; |
| 178 | + StackTraceElement ste = stackTrace[indexPlus]; |
| 179 | + return builder |
| 180 | + .setFile(ste.getFileName()) |
| 181 | + .setLine(Long.valueOf(ste.getLineNumber())) |
| 182 | + .setFunction(ste.getMethodName()) |
| 183 | + .build(); |
| 184 | + } |
157 | 185 | }
|
0 commit comments