SwiftSentry

1.0.0

Native Swift implementation to log to Sentry.io
petrpavlik/swift-sentry

What's New

1.0.0

2024-05-18T15:55:47Z

SwiftSentry

Swift 5 SPM Platforms Test codebeat badge

Log messages from Swift to Sentry following SwiftLog.

Usage

  1. Add SwiftSentry as a dependency to your Package.swift
  dependencies: [
    .package(name: "SwiftSentry", url: "https://github.com/swift-sentry/swift-sentry.git", from: "1.0.0")
  ],
  targets: [
    .target(name: "MyApp", dependencies: ["SwiftSentry"])
  ]
  1. Configure Logging system
import Logging
import SwiftSentry

let sentry = Sentry(dsn: "<Your Sentry DSN String>")

// Add sentry to logger and set the minimum log level to `.error`
LoggingSystem.bootstrap { label in
    MultiplexLogHandler([
        SentryLogHandler(label: label, sentry: sentry, level: .error),
        StreamLogHandler.standardOutput(label: label)
    ])
}

If your application already uses a EventLoopGroup it is recommended to share it with SwiftSentry:

let sentry = try Sentry(
  dsn: "<Your Sentry DSN String>",
  httpClient: HTTPClient(eventLoopGroupProvider: .shared(eventLoopGroup))
)
  1. Send logs
var logger = Logger(label: "com.example.MyApp.main")
logger.critical("Something went wrong!")

The metadata of the logger will be sent as tags to sentry.

logger[metadataKey: "note"] = Logger.MetadataValue(stringLiteral: "some usefull information")

Upload crash reports

SwiftSentry can also upload stack traces generated on Linux with Swift Backtrace.

The following configuration assumes that you run an "API service" based on Swift with supervisord following a typical vapor deployment.

Stack traces are uploaded at each start of your "API service". If your application crashes, a stack trace will be printed on stderr and written to a log file specified in supervisord. Once your application is restarted, SwiftSentry will read this log file and upload it to Sentry.

import SwiftSentry

let sentry = Sentry(dsn: "<Your Sentry DSN String>")

// Upload stack trace from a log file
// WARNING: the error file will be truncated afterwards
_ = try? sentry.uploadStackTrace(path: "/var/log/supervisor/hello-stderr.log")

Supervisor configuration at /etc/supervisor/conf.d/hello.conf:

[program:hello]
command=/home/vapor/hello/.build/release/Run serve --env production
directory=/home/vapor/hello/
user=vapor
stdout_logfile=/var/log/supervisor/%(program_name)-stdout.log
stderr_logfile=/var/log/supervisor/%(program_name)-stderr.log

TODO

  • Capture stack traces for all logs (See Vapor Stacktrace implementation)
  • Additional repository SentryVapor to abtract logging with vapor requests. E.g. log hostnames, url, request-id

Description

  • Swift Tools 5.10.0
View More Packages from this Author

Dependencies

Last updated: Sat Nov 02 2024 17:53:05 GMT-0900 (Hawaii-Aleutian Daylight Time)