-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
634892f
commit 7932e5e
Showing
2 changed files
with
57 additions
and
22 deletions.
There are no files selected for viewing
51 changes: 51 additions & 0 deletions
51
src/OpenTelemetry.AutoInstrumentation.AspNetCore.Plugins/ActivitySourceExtenstion.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
using System.Diagnostics; | ||
using Microsoft.AspNetCore.Diagnostics; | ||
using Microsoft.AspNetCore.Http; | ||
using OpenTelemetry.Trace; | ||
|
||
namespace OpenTelemetry.AutoInstrumentation.AspNetCore.Plugins; | ||
|
||
public static class ActivitySourceExtenstion | ||
{ | ||
public static Action<Activity, HttpResponse> EnrichHttpResponse() | ||
{ | ||
return (activity, response) => | ||
{ | ||
var exceptionHandlerPathFeature = response.HttpContext.Features.Get<IExceptionHandlerPathFeature>(); | ||
if (exceptionHandlerPathFeature == null) | ||
{ | ||
return; | ||
} | ||
|
||
var exception = exceptionHandlerPathFeature.Error; | ||
activity.SetStatus(ActivityStatusCode.Error, exception.Message); | ||
activity.RecordException(exception); | ||
}; | ||
} | ||
|
||
public static Action<Activity, HttpRequest> EnrichHttpRequest() | ||
{ | ||
return (activity, request) => | ||
{ | ||
// 記錄使用者 IP | ||
var clientIp = request.Headers["X-Forwarded-For"].FirstOrDefault(); | ||
|
||
if (string.IsNullOrWhiteSpace(clientIp)) | ||
{ | ||
var remoteIp = request.HttpContext.Connection.RemoteIpAddress; | ||
|
||
if (remoteIp != null) | ||
{ | ||
clientIp = remoteIp.MapToIPv4().ToString(); | ||
|
||
if (clientIp.StartsWith("::ffff:", StringComparison.OrdinalIgnoreCase)) | ||
{ | ||
clientIp = clientIp.ToLower().Replace("::ffff:", ""); | ||
} | ||
} | ||
} | ||
|
||
activity.SetTag("http.client.ip", clientIp); | ||
}; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters