Exemplo n.º 1
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteStringArrayIfNotEmpty("pre_context", InternalPreContext);
            writer.WriteStringArrayIfNotEmpty("post_context", InternalPostContext);
            writer.WriteStringDictionaryIfNotEmpty("vars", InternalVars !);
            writer.WriteArrayIfNotEmpty("frames_omitted", InternalFramesOmitted?.Cast <object>(), logger);
            writer.WriteStringIfNotWhiteSpace("filename", FileName);
            writer.WriteStringIfNotWhiteSpace("function", Function);
            writer.WriteStringIfNotWhiteSpace("module", Module);
            writer.WriteNumberIfNotNull("lineno", LineNumber);
            writer.WriteNumberIfNotNull("colno", ColumnNumber);
            writer.WriteStringIfNotWhiteSpace("abs_path", AbsolutePath);
            writer.WriteStringIfNotWhiteSpace("context_line", ContextLine);
            writer.WriteBooleanIfNotNull("in_app", InApp);
            writer.WriteStringIfNotWhiteSpace("package", Package);
            writer.WriteStringIfNotWhiteSpace("platform", Platform);
            writer.WriteNumberIfNotNull("image_addr", ImageAddress.NullIfDefault());
            writer.WriteNumberIfNotNull("symbol_addr", SymbolAddress);
            writer.WriteStringIfNotWhiteSpace("instruction_addr", InstructionAddress);
            writer.WriteNumberIfNotNull("instruction_offset", InstructionOffset);

            writer.WriteEndObject();
        }
Exemplo n.º 2
0
 public NLogDiagnosticLogger(IDiagnosticLogger?extraLogger = null)
 {
     if (!InternalLogger.LogToConsole || !(extraLogger is ConsoleDiagnosticLogger))
     {
         _extraLogger = extraLogger;
     }
 }
Exemplo n.º 3
0
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteNumber("allocated_bytes", AllocatedBytes);
            writer.WriteNumber("fragmented_bytes", FragmentedBytes);
            writer.WriteNumber("heap_size_bytes", HeapSizeBytes);
            writer.WriteNumber("high_memory_load_threshold_bytes", HighMemoryLoadThresholdBytes);
            writer.WriteNumber("total_available_memory_bytes", TotalAvailableMemoryBytes);
            writer.WriteNumber("memory_load_bytes", MemoryLoadBytes);

#if NET5_0_OR_GREATER
            writer.WriteNumber("total_committed_bytes", TotalCommittedBytes);
            writer.WriteNumber("promoted_bytes", PromotedBytes);
            writer.WriteNumber("pinned_objects_count", PinnedObjectsCount);
            writer.WriteNumber("pause_time_percentage", PauseTimePercentage);
            writer.WriteNumber("index", Index);
            writer.WriteNumber("generation", Generation);
            writer.WriteNumber("finalization_pending_count", FinalizationPendingCount);
            writer.WriteBoolean("compacted", Compacted);
            writer.WriteBoolean("concurrent", Concurrent);
            writer.WritePropertyName("pause_durations");
            writer.WriteStartArray();
            foreach (var duration in PauseDurations)
            {
                writer.WriteNumberValue(duration.TotalMilliseconds);
            }
            writer.WriteEndArray();
#endif
            writer.WriteEndObject();
        }
Exemplo n.º 4
0
        private async Task <MemoryStream> BufferPayloadAsync(IDiagnosticLogger?logger, CancellationToken cancellationToken = default)
        {
            var buffer = new MemoryStream();
            await Payload.SerializeAsync(buffer, logger, cancellationToken).ConfigureAwait(false);

            buffer.Seek(0, SeekOrigin.Begin);

            return(buffer);
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteStringIfNotWhiteSpace("name", Name);
            writer.WriteStringIfNotWhiteSpace("version", Version);

            writer.WriteEndObject();
        }
Exemplo n.º 6
0
        internal bool ContainsSentry(string main, IDiagnosticLogger?logger)
        {
            if (main.Contains(Include))
            {
                logger?.LogInfo("'main.mm' already contains Sentry.");
                return(true);
            }

            return(false);
        }
Exemplo n.º 7
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteSerializable("event_id", EventId, logger);
            writer.WriteStringIfNotWhiteSpace("name", Name);
            writer.WriteStringIfNotWhiteSpace("email", Email);
            writer.WriteStringIfNotWhiteSpace("comments", Comments);

            writer.WriteEndObject();
        }
Exemplo n.º 8
0
        public void AddBuildPhaseSymbolUpload(IDiagnosticLogger?logger)
        {
            if (MainTargetContainsSymbolUploadBuildPhase())
            {
                logger?.LogDebug("Build phase '{0}' already added.", SymbolUploadPhaseName);
                return;
            }

            _pbxProjectType.GetMethod("AddShellScriptBuildPhase", new[] { typeof(string), typeof(string), typeof(string), typeof(string) })
            .Invoke(_project, new object[] { _mainTargetGuid, SymbolUploadPhaseName, "/bin/sh", _uploadScript });
        }
Exemplo n.º 9
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteNumberIfNotNull("id", Id);
            writer.WriteStringIfNotWhiteSpace("name", Name);
            writer.WriteBooleanIfNotNull("crashed", Crashed);
            writer.WriteBooleanIfNotNull("current", Current);
            writer.WriteSerializableIfNotNull("stacktrace", Stacktrace, logger);

            writer.WriteEndObject();
        }
Exemplo n.º 10
0
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteNumber("min_worker_threads", MinWorkerThreads);
            writer.WriteNumber("min_completion_port_threads", MinCompletionPortThreads);
            writer.WriteNumber("max_worker_threads", MaxWorkerThreads);
            writer.WriteNumber("max_completion_port_threads", MaxCompletionPortThreads);
            writer.WriteNumber("available_worker_threads", AvailableWorkerThreads);
            writer.WriteNumber("available_completion_port_threads", AvailableCompletionPortThreads);

            writer.WriteEndObject();
        }
Exemplo n.º 11
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteDictionaryIfNotEmpty("data", InternalData !, logger);
            writer.WriteDictionaryIfNotEmpty("meta", InternalMeta !, logger);
            writer.WriteStringIfNotWhiteSpace("type", Type);
            writer.WriteStringIfNotWhiteSpace("description", Description);
            writer.WriteStringIfNotWhiteSpace("help_link", HelpLink);
            writer.WriteBooleanIfNotNull("handled", Handled);

            writer.WriteEndObject();
        }
Exemplo n.º 12
0
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteSerializable("update", Update, logger);

            if (PauseTimestamp is { } pauseTimestamp)
            {
                writer.WriteString("paused", pauseTimestamp);
            }

            writer.WriteEndObject();
        }
Exemplo n.º 13
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteStringIfNotWhiteSpace("type", Type);
            writer.WriteStringIfNotWhiteSpace("value", Value);
            writer.WriteStringIfNotWhiteSpace("module", Module);
            writer.WriteNumberIfNotNull("thread_id", ThreadId.NullIfDefault());
            writer.WriteSerializableIfNotNull("stacktrace", Stacktrace, logger);
            writer.WriteSerializableIfNotNull("mechanism", Mechanism, logger);

            writer.WriteEndObject();
        }
Exemplo n.º 14
0
        private async Task SerializeHeaderAsync(Stream stream, IDiagnosticLogger?logger, CancellationToken cancellationToken = default)
        {
            var writer = new Utf8JsonWriter(stream);

#if NET461 || NETSTANDARD2_0
            using (writer)
#else
            await using (writer.ConfigureAwait(false))
#endif
            {
                writer.WriteDictionaryValue(Header, logger);
                await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 15
0
        /// <inheritdoc />
        public async Task SerializeAsync(Stream stream, IDiagnosticLogger?logger, CancellationToken cancellationToken = default)
        {
            // Header
            await SerializeHeaderAsync(stream, logger, cancellationToken).ConfigureAwait(false);

            await stream.WriteByteAsync((byte)'\n', cancellationToken).ConfigureAwait(false);

            // Items
            foreach (var item in Items)
            {
                await item.SerializeAsync(stream, logger, cancellationToken).ConfigureAwait(false);

                await stream.WriteByteAsync((byte)'\n', cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 16
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteStringDictionaryIfNotEmpty("env", InternalEnv !);
            writer.WriteStringDictionaryIfNotEmpty("other", InternalOther !);
            writer.WriteStringDictionaryIfNotEmpty("headers", InternalHeaders !);
            writer.WriteStringIfNotWhiteSpace("url", Url);
            writer.WriteStringIfNotWhiteSpace("method", Method);
            writer.WriteDynamicIfNotNull("data", Data, logger);
            writer.WriteStringIfNotWhiteSpace("query_string", QueryString);
            writer.WriteStringIfNotWhiteSpace("cookies", Cookies);

            writer.WriteEndObject();
        }
Exemplo n.º 17
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteString(
                "timestamp",
                Timestamp.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffZ", DateTimeFormatInfo.InvariantInfo));

            writer.WriteStringIfNotWhiteSpace("message", Message);
            writer.WriteStringIfNotWhiteSpace("type", Type);
            writer.WriteStringDictionaryIfNotEmpty("data", Data !);
            writer.WriteStringIfNotWhiteSpace("category", Category);
            writer.WriteStringIfNotWhiteSpace("level", Level.NullIfDefault()?.ToString().ToLowerInvariant());

            writer.WriteEndObject();
        }
Exemplo n.º 18
0
 /// <summary>
 /// Attempts to serialize
 /// </summary>
 /// <param name="value"></param>
 /// <param name="logger"></param>
 /// <returns></returns>
 public static string?SerializeSafely(object value, IDiagnosticLogger?logger = null)
 {
     if (value is string stringValue)
     {
         // Otherwise it'll return ""value""
         return(stringValue);
     }
     try
     {
         return(JsonSerializer.Serialize(value));
     }
     catch (Exception e)
     {
         logger?.LogError("Failed to serialize value of type \"{0}\"", e, value.GetType());
         return(null);
     }
 }
Exemplo n.º 19
0
        public void AddSentry(string pathToMain, IDiagnosticLogger?logger)
        {
            if (!File.Exists(pathToMain))
            {
                throw new FileNotFoundException("Could not find main.", pathToMain);
            }

            var main = File.ReadAllText(pathToMain);

            if (ContainsSentry(main, logger))
            {
                return;
            }

            var sentryMain = AddSentryToMain(main);

            File.WriteAllText(pathToMain, sentryMain);
        }
Exemplo n.º 20
0
        public bool IsValid(IDiagnosticLogger?logger, bool?isDevelopmentBuild = null)
        {
            if (!UploadSymbols)
            {
                logger?.LogDebug("sentry-cli: Automated symbols upload has been disabled.");
                return(false);
            }

            if ((isDevelopmentBuild ?? EditorUserBuildSettings.development) && !UploadDevelopmentSymbols)
            {
                logger?.LogDebug("sentry-cli: Automated symbols upload for development builds has been disabled.");
                return(false);
            }

            var validated = true;

            if (string.IsNullOrWhiteSpace(Auth))
            {
                MissingFieldWarning(logger, "Auth name");
                validated = false;
            }

            if (string.IsNullOrWhiteSpace(Organization))
            {
                MissingFieldWarning(logger, "Organization");
                validated = false;
            }

            if (string.IsNullOrWhiteSpace(Project))
            {
                MissingFieldWarning(logger, "Project");
                validated = false;
            }

            if (!validated)
            {
                logger?.LogWarning("sentry-cli validation failed. Symbols will not be uploaded." +
                                   "\nYou can disable this warning by disabling the automated symbols upload under " +
                                   EditorMenuPath);
            }

            return(validated);
        }
Exemplo n.º 21
0
        internal static void AddExecutableToXcodeProject(string projectPath, IDiagnosticLogger? logger)
        {
            var executableSource = GetSentryCliPath(SentryCliMacOS);
            var executableDestination = Path.Combine(projectPath, SentryCliMacOS);

            if (!Directory.Exists(projectPath))
            {
                throw new DirectoryNotFoundException($"Xcode project directory not found at {executableDestination}");
            }

            if (File.Exists(executableDestination))
            {
                logger?.LogDebug("sentry-cli executable already found at {0}", executableDestination);
                return;
            }

            File.Copy(executableSource, executableDestination);
            SetExecutePermission(executableDestination);
        }
Exemplo n.º 22
0
        internal static void CopyFile(string sourcePath, string targetPath, IDiagnosticLogger?logger)
        {
            if (File.Exists(targetPath))
            {
                logger?.LogDebug("'{0}' has already been copied to '{1}'", Path.GetFileName(targetPath), targetPath);
                return;
            }

            if (File.Exists(sourcePath))
            {
                logger?.LogDebug("Copying from: '{0}' to '{1}'", sourcePath, targetPath);

                Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(targetPath)));
                FileUtil.CopyFileOrDirectory(sourcePath, targetPath);
            }

            if (!File.Exists(targetPath))
            {
                throw new FileNotFoundException($"Failed to copy '{sourcePath}' to '{targetPath}'");
            }
        }
Exemplo n.º 23
0
        internal static SentryCommandInterceptor?UseBreadcrumbs(
            IQueryLogger?queryLogger           = null,
            bool initOnce                      = true,
            IDiagnosticLogger?diagnosticLogger = null)
        {
            if (initOnce && Interlocked.Exchange(ref Init, 1) != 0)
            {
                diagnosticLogger?.LogWarning("{0}.{1} was already executed.",
                                             nameof(SentryDatabaseLogging), nameof(UseBreadcrumbs));
                return(null);
            }

            diagnosticLogger?.LogInfo("{0}.{1} adding interceptor.",
                                      nameof(SentryDatabaseLogging), nameof(UseBreadcrumbs));

            queryLogger ??= new SentryQueryLogger();
            var interceptor = new SentryCommandInterceptor(queryLogger);

            DbInterception.Add(interceptor);
            return(interceptor);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Creates an envelope that contains a single event.
        /// </summary>
        public static Envelope FromEvent(
            SentryEvent @event,
            IDiagnosticLogger?logger = null,
            IReadOnlyCollection <Attachment>?attachments = null,
            SessionUpdate?sessionUpdate = null)
        {
            var header = CreateHeader(@event.EventId);

            var items = new List <EnvelopeItem>
            {
                EnvelopeItem.FromEvent(@event)
            };

            if (attachments is not null)
            {
                foreach (var attachment in attachments)
                {
                    try
                    {
                        items.Add(EnvelopeItem.FromAttachment(attachment));
                    }
                    catch (Exception exception)
                    {
                        if (logger is null)
                        {
                            throw;
                        }

                        logger.LogError("Failed to add attachment: {0}.", exception, attachment.FileName);
                    }
                }
            }

            if (sessionUpdate is not null)
            {
                items.Add(EnvelopeItem.FromSession(sessionUpdate));
            }

            return(new Envelope(header, items));
        }
Exemplo n.º 25
0
        /// <inheritdoc />
        public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger?logger)
        {
            writer.WriteStartObject();

            writer.WriteSerializable("sid", Id, logger);
            writer.WriteStringIfNotWhiteSpace("did", DistinctId);
            writer.WriteBoolean("init", IsInitial);
            writer.WriteString("started", StartTimestamp);
            writer.WriteString("timestamp", Timestamp);
            writer.WriteNumber("seq", SequenceNumber);
            writer.WriteNumber("duration", (int)Duration.TotalSeconds);
            writer.WriteNumber("errors", ErrorCount);
            writer.WriteStringIfNotWhiteSpace("status", EndStatus?.ToString().ToSnakeCase());

            // Attributes
            writer.WriteStartObject("attrs");
            writer.WriteString("release", Release);
            writer.WriteStringIfNotWhiteSpace("environment", Environment);
            writer.WriteStringIfNotWhiteSpace("ip_address", IpAddress);
            writer.WriteStringIfNotWhiteSpace("user_agent", UserAgent);
            writer.WriteEndObject();

            writer.WriteEndObject();
        }
Exemplo n.º 26
0
        /// <inheritdoc />
        public async Task SerializeAsync(Stream stream, IDiagnosticLogger?logger, CancellationToken cancellationToken = default)
        {
            // Length is known
            if (TryGetLength() != null)
            {
                // Header
                await SerializeHeaderAsync(stream, logger, cancellationToken).ConfigureAwait(false);

                await stream.WriteByteAsync((byte)'\n', cancellationToken).ConfigureAwait(false);

                // Payload
                await Payload.SerializeAsync(stream, logger, cancellationToken).ConfigureAwait(false);
            }
            // Length is NOT known (need to calculate)
            else
            {
                var payloadBuffer = await BufferPayloadAsync(logger, cancellationToken).ConfigureAwait(false);

#if NET461 || NETSTANDARD2_0
                using (payloadBuffer)
#else
                await using (payloadBuffer.ConfigureAwait(false))
#endif
                {
                    // Header
                    var headerWithLength = Header.ToDictionary();
                    headerWithLength[LengthKey] = payloadBuffer.Length;
                    await SerializeHeaderAsync(stream, headerWithLength, logger, cancellationToken).ConfigureAwait(false);

                    await stream.WriteByteAsync((byte)'\n', cancellationToken).ConfigureAwait(false);

                    // Payload
                    await payloadBuffer.CopyToAsync(stream, cancellationToken).ConfigureAwait(false);
                }
            }
        }
 public void AddSentry(string pathToMain, IDiagnosticLogger?logger)
 {
 }
Exemplo n.º 28
0
 private static void MissingFieldWarning(IDiagnosticLogger?logger, string name) =>
 logger?.LogWarning("sentry-cli: {0} missing. Please set it under {1}", name, EditorMenuPath);
Exemplo n.º 29
0
        public static void WriteToFile(this IJsonSerializable serializable, string filePath, IDiagnosticLogger?logger)
        {
            using var file   = File.Create(filePath);
            using var writer = new Utf8JsonWriter(file);

            serializable.WriteTo(writer, logger);
            writer.Flush();
        }
Exemplo n.º 30
0
 private async Task SerializeHeaderAsync(
     Stream stream,
     IDiagnosticLogger?logger,
     CancellationToken cancellationToken = default) =>
 await SerializeHeaderAsync(stream, Header, logger, cancellationToken).ConfigureAwait(false);