namespace Yuanshen.SDK.Handlers; public static class TelemetryHandler { private const int PreviewLimit = 1200; private static readonly object FileLock = new(); private static readonly string LogPath = Path.Combine(AppContext.BaseDirectory, "client-telemetry.log"); public static async Task OnLog(HttpRequest request) { string body = await BodyAsync(request); Append(request.Path, body); Log.Info($"telemetry {request.Path} {body}"); return TypedResults.Text("{\"code\":0}", "application/json"); } private static void Append(string path, string body) { try { lock (FileLock) File.AppendAllText(LogPath, $"{DateTime.Now:HH:mm:ss} {path} {body}{Environment.NewLine}"); } catch (IOException) { } } public static async Task OnUnhandled(HttpRequest request) { string path = $"{request.Path}{request.QueryString}"; Log.Unhandled(request.Method, path); if (HttpMethods.IsPost(request.Method) || HttpMethods.IsPut(request.Method)) Log.Info($"body {await BodyAsync(request)}"); return TypedResults.Text("{\"retcode\":0,\"message\":\"OK\",\"data\":null}", "application/json"); } private static async Task BodyAsync(HttpRequest request) { using StreamReader reader = new(request.Body, leaveOpen: true); string body = (await reader.ReadToEndAsync()).ReplaceLineEndings(" "); if (body.Length == 0) return ""; return body.Length <= PreviewLimit ? body : body[..PreviewLimit] + $"... (+{body.Length - PreviewLimit} bytes)"; } }